Proposal: add ifM and whenM to Control.Monad

Andreas Abel andreas.abel at ifi.lmu.de
Sun Apr 20 19:38:13 UTC 2014


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

+1 for both, plus

unlessM :: (Monad m) => m Bool -> m () -> m ()
unlessM mc ma = ifM mc (return ()) ma

(See, for instance,
https://hackage.haskell.org/package/Agda-2.3.2.2/docs/Agda-Utils-Monad.html
.)

On 20.04.2014 21:10, 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 ()
> 
> 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
> 


- -- 
Andreas Abel  <><      Du bist der geliebte Mensch.

Department of Computer Science and Engineering
Chalmers and Gothenburg University, Sweden

andreas.abel at gu.se
http://www2.tcs.ifi.lmu.de/~abel/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlNUIiQACgkQPMHaDxpUpLMkiQCgwwUfJ/orQ9GNB3SsStc1SB/4
F/kAn0AZ04HBeRjlNk7QkZcjHZ6Am+37
=EBzJ
-----END PGP SIGNATURE-----


More information about the Libraries mailing list