Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit main in haskell given a condition

I have a main function that does a lot of IO. At one point, however, I want to check a variable like not (null shouldBeNull) exit the whole program, without continuing, with a linux exitcode 1 and output an error message.

I've tried playing around with error "..." like putting that in an if:

if (not (null shouldBeNull)) error "something bad happened" else putStrLn "ok"

but I get a parse error (possibly incorrect indentation) :(.

Here's an altered snippet.

main :: IO ExitCode
main = do 
  --Get the file name using program argument
  args <- getArgs
  file <- readFile (args !! 0)
  putStrLn("\n")
  -- ... (some other io)
  -- [DO A CHECK HERE], exit according to check..
  -- ... (even more io)
  echotry <- system "echo success"
  rmtry <- system "rm -f test.txt"
  system "echo done."

As you may notice, I want to do the check where I've put [DO A CHECK HERE] comment above...

Thanks for your help!

like image 468
meltuhamy Avatar asked Nov 19 '11 20:11

meltuhamy


Video Answer


1 Answers

The parse error is because you're missing the then keyword in your if expression.

if condition then truePart else falsePart

For exiting, a more appropriate choice than error might be to use one of the functions from System.Exit, for example exitFailure.

So for example,

if not $ null shouldBeNull
    then do putStrLn "something bad happened"
            exitFailure
    else putStrLn "ok"
like image 157
hammar Avatar answered Sep 20 '22 06:09

hammar