Felipe Almeida Lessa | 26 Jan 20:43 2013
Picon

Use forM_ with Maybe, it's Foldable!

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)

Felipe Almeida Lessa | 27 Jan 00:09 2013
Picon

Re: Use forM_ with Maybe, it's Foldable!

Herbert Valerio actually pointed out to me in PVT that funnily enough
I've actually *forgotten* and *rediscovered* this idiom! =)

  http://www.haskell.org/pipermail/libraries/2011-November/017257.html

Cheers!

On Sat, Jan 26, 2013 at 5:43 PM, Felipe Almeida Lessa
<felipe.lessa <at> gmail.com> wrote:
> 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:
>
(Continue reading)

John Wiegley | 27 Jan 06:55 2013

Re: Use forM_ with Maybe, it's Foldable!

>>>>> Felipe Almeida Lessa <felipe.lessa <at> gmail.com> writes:

> 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_

You can also use "for_", if you want to use Applicative instead of Monad.

--

-- 
John Wiegley
FP Complete                         Haskell tools, training and consulting
http://fpcomplete.com               johnw on #haskell/irc.freenode.net

Gmane