a monadic if or case?

Arjan van IJzendoorn afie@cs.uu.nl
Thu, 13 Feb 2003 15:32:52 +0100

> whatisit :: String -> IO String
> whatisit f = do
>   ifM doesDirectoryExist f
>       then return "dir"
>       else ifM doesFileExist f
>            then return "file"
>            else return "nothing"
> Is there any way I could do something like this?

Not with the syntactic sugar of 'if'.
But you can write [warning: untested code ahead]

ifM :: IO Bool -> IO a -> IO a -> IO a
ifM test yes no = do 
   b <- test
   if b then yes else no

And then

ifM (doesDirectoryExist f)
  (return "dir")
  (ifM (doesFileExist f) 
           (return "file")
           (return "nothing))