16

Possible Duplicate:
Haskell “do nothing” IO, or if without else

Something got wrong in these "easy" lines ...

action = do
    isdir <- doesDirectoryExist path  -- check if directory exists.
    if(not isdir)                     
        then do handleWrong
    doOtherActions                    -- compiling ERROR here.

GHCi will complaint about identifiers , or do not exec the last line action after I add else do .

I think exception handling may work, but is it necessary in such common "check and do something" statements ?

Thanks.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
snowmantw
  • 1,611
  • 1
  • 13
  • 25

1 Answers1

36

if in Haskell must always have a then and an else. So this will work:

action = do
    isdir <- doesDirectoryExist path
    if not isdir
        then handleWrong
        else return ()     -- i.e. do nothing
    doOtherActions

Equivalently, you can use when from Control.Monad:

action = do
    isdir <- doesDirectoryExist path
    when (not isdir) handleWrong
    doOtherActions

Control.Monad also has unless:

action = do
    isdir <- doesDirectoryExist path
    unless isdir handleWrong
    doOtherActions

Note that when you tried

action = do
    isdir <- doesDirectoryExist path
    if(not isdir)
        then do handleWrong
        else do
    doOtherActions

it was parsed as

action = do
    isdir <- doesDirectoryExist path
    if(not isdir)
        then do handleWrong
        else do doOtherActions
Will Ness
  • 70,110
  • 9
  • 98
  • 181
dave4420
  • 46,404
  • 6
  • 118
  • 152
  • using [`when`](https://hackage.haskell.org/package/base-4.17.0.0/docs/Control-Monad.html#v:when) seems to be cleaner – aurelia Nov 27 '22 at 16:48