26 Jan 2013 20:43
Use forM_ with Maybe, it's Foldable!
Felipe Almeida Lessa <felipe.lessa <at> gmail.com>
2013-01-26 19:43:24 GMT
2013-01-26 19:43:24 GMT
Hey,
Just wanted to share this little insight I had that I don't think is a
common idiom. Often times I need to define:
whenJust :: Monad m => Maybe a -> (a -> m b) -> m ()
whenJust (Just x) f = f x
whenJust Nothing _ = return ()
It always bugged me that you can't find this function anywhere.
Actually, you can find it on at least a couple of packages [1], but
you can't find it on a standard place. Or can you?
A few days ago I decided to hoogle the type of whenJust [2] and what I
discovered is that
import Data.Foldable (forM_)
whenJust = forM_
For example, instead of:
mfoo <- doSomething
case mfoo of
Just foo -> ...
Nothing -> return ()
You may just write:
forM_ mfoo $ \foo ->
...
(Continue reading)
RSS Feed