Proposal: add ifM and whenM to Control.Monad

Mario Pastorelli pastorelli.mario at gmail.com
Sun Apr 20 20:26:02 UTC 2014


Hi Herbert,

in general I like pattern matching but not when boolean values are 
involved. Your code is nice but, in my opinion, still far from the 
elegance of

f = unlessM (doesDirectoryExist path) $ do
           putStrLn $ "Creating directory " ++ path
           createDirectory path

In particular, note that I don't have to take care of the False case and 
the code doesn't have boilerplate.

While your solution is more general, I would like to point out that when 
and unless are so useful that they got their own functions in the 
library instead of relying on pattern matching. I consider ifM, whenM 
and unlessM as alternate versions of existing functions.

On 04/20/2014 09:59 PM, Herbert Valerio Riedel wrote:
> Hi Mario,
>
> On 2014-04-20 at 21:10:03 +0200, Mario Pastorelli wrote:
>> I would like to propose the addition of two new combinators to
>> Control.Monad:
>>
>> ifM :: (Monad m) => m Bool -> m a -> m a -> m a
>> whenM :: (Monad m) => m Bool -> m () -> m ()
> [...]
>
>> f = do
>>      dirDoesntExist <- not <$> doesDirectoryExist path
>>      when dirDoesntExist $ do
>>        putStrLn $ "Creating directory " ++ path
>>        createDirectory path
> While I'm neutral on this proposal, I'd like to remind that LambdaCase
> may be useful to avoid temporary variables as well (and is even more
> useful for types other than Bool):
>
>    f = doesDirectoryExist path >>= \case
>          True  -> return ()
>          False -> do
>            putStrLn $ "Creating directory " ++ path
>            createDirectory path
>    
> Cheers,
>    hvr



More information about the Libraries mailing list