I am porting a Java application to Haskell. The main method of the Java application follows the pattern:
public static void main(String [] args)
{
if (args.length == 0)
{
System.out.println("Invalid number of arguments.");
System.exit(1);
}
SomeDataType d = getData(arg[0]);
if (!dataOk(d))
{
System.out.println("Could not read input data.");
System.exit(1);
}
SomeDataType r = processData(d);
if (!resultOk(r))
{
System.out.println("Processing failed.");
System.exit(1);
}
...
}
So I have different steps and after each step I can either exit with an error code, or continue to the following step.
My attempt at porting this to Haskell goes as follows:
main :: IO ()
main = do
a <- getArgs
if (null args)
then do
putStrLn "Invalid number of arguments."
exitWith (ExitFailure 1)
else do
-- The rest of the main function goes here.
With this solution, I will have lots of nested if-then-else
(one for each exit point of the original Java code).
Is there a more elegant / idiomatic way of implementing this pattern in Haskell? In general, what is a Haskell idiomatic way to implement an early exit / return as used in an imperative language like Java?
length
. Usenull
if you actually need to simply check, but prefer pattern matching, because that combines the check with giving a name to the list element(s) so you can use them. – Idolizenull
.length
slipped in from the Java original and I did not care too much about it because I expect the list of arguments to be rather short. But, yes,null
is definitely the way to go. – Neology