Proposal: add ifM and whenM to Control.Monad

Edward Kmett ekmett at gmail.com
Sun Apr 20 19:47:19 UTC 2014


These come up every few months.

Historically, I've always been -1 on their inclusion as they are simple
compositions of more fundamental operations.

However, given that they keep getting reinvented with the exact same names
and functionality. I'm finally ready to give in.

+1 from me.

-Edward


On Sun, Apr 20, 2014 at 3:10 PM, Mario Pastorelli <
pastorelli.mario at gmail.com> 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 ()
>
> The reason is that when you work in a `Monad m` the first argument of `if`
> and `when` is often a `m Bool` and not a `Bool`. In those cases, you have
> to write:
>
> monadicOperationReturningBool >>= \b -> when b doAnotherMonadicOperation
>
> or
>
> monadicOperationReturningBool >>= flip when doAnotherMonadicOperation
>
> to accomplish what you want to do. If you use the do-notation this is less
> terrible but you still need to assign a name to the boolean value. Take for
> example:
>
> f = do
>     dirDoesntExist <- not <$> doesDirectoryExist path
>     when dirDoesntExist $ do
>       putStrLn $ "Creating directory " ++ path
>       createDirectory path
>
> in this snippet, dirDoesntExist is completely useless and its only purpose
> it to be used in the next expression. With the new combinators you could
> write:
>
> f = whenM (not <$> doesDirectoryExists path) $ do
>         putStrLn $ "Creating directory " ++ path
>         createDirectory path
>
> Many libraries on hackage already include these functions (I often use
> Control.Conditional). For a list see http://holumbus.fh-wedel.de/
> hayoo/hayoo.html?query=whenM&start=0.
> _______________________________________________
> Libraries mailing list
> Libraries at haskell.org
> http://www.haskell.org/mailman/listinfo/libraries
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/libraries/attachments/20140420/9ace1a26/attachment.html>


More information about the Libraries mailing list