[Haskell-cafe] Re: Equivalent of if/then/else for IO Bool?

Benjamin Franksen benjamin.franksen at bessy.de
Thu Nov 23 17:00:34 EST 2006


Dougal Stanton 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')
> 
> Or maybe there's a more sensible way of doing the above that I've
> missed. I seem to use endless alternate conditions sometimes and there's
> bound to be a better way.

Roll your own control structures! Haskell has higher order functions for a
reason. This should do the trick (untested):

condM condAction thenBranch elseBranch = do
  bool <- condAction
  if bool
    then thenBranch
    else elseBranch

(Hack it into ghci or hugs to find out the type, it's a bit more general
than what you need.)

Cheers
Ben



More information about the Haskell-Cafe mailing list