How to implement early exit / return in Haskell?
- by Giorgio
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 ((length args) == 0)
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?