[Haskell-cafe] Equivalent of if/then/else for IO Bool?
ctm at cs.nott.ac.uk
Thu Nov 23 18:01:01 EST 2006
Jason Dagit wrote:
> On 11/23/06, Dougal Stanton <ithika at gmail.com> 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
More care required!
More information about the Haskell-Cafe