Jason Dagit wrote:
On 11/23/06, Dougal Stanton <[EMAIL PROTECTED]> wrote:
Is there some sort of equivalent of the if/then/else construct for use
in the IO monad? For instance the following can get quite tedious:

> do bool <- doesFileExist filename
>    if bool
>    then sth
>    else sth'

Is there a more compact way of writing that? Something akin to:

> condM (doesFileExist filename) (sth) (sth')

Maybe there is one built in but don't know it or see anything in
hoogle. I'd use something like the following (and then just make it a
standard part of the libraries I use personally):

import Control.Monad

if' b t e = if b then t else e
ifM = liftM3 if'

which gives ifM :: (Monad m) => m Bool -> m t -> m t -> m t

No! You can really screw up this way...

Your function will perform the effects of the Bool and *both* branch computation in sequence, then use the returned Bool value to select between the returned 'then' value and the returned 'else' value. Do not use it to operate machinery!

*Grr> ifM (Just True) (Just 3) Nothing
Nothing

More care required!

Conor

_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to