[Haskell-beginners] How Best to Deal with Nested Monads?

David McBride dmcbride at neondsl.com
Thu Sep 15 01:46:02 CEST 2011


Try this?

import Data.Maybe (isNothing)
import Control.Monad (filterM)

lst >>= (fmap getC $ filterM $ fmap isNothing . getMB)

On Wed, Sep 14, 2011 at 6:48 PM, Michael Craig <mkscrg at gmail.com> wrote:
> Say we've got these types
> lst :: m [a]
> getMB :: a -> m (Maybe b)
> getC :: b -> m c
> and we want to map getMB and getC over the elements of lst, all the while
> discarding elements x where getMB x == Nothing.
> (This could be generalized more by replacing Maybe with some monad m', but
> let's run with Maybe because it's easy to talk about.)
> The best I've got (after some help on IRC) is this not-so-easy-to-read
> oneliner:
> lst >>= (\x -> mapM (liftM (liftM getC) (getMB x)) >>= sequence . catMaybes
> This is hard to read, but it's also bad because we run sequence twice (once
> inside of mapM). If we want to do multiple things to each element of lst, it
> would be nice to process each element completely before moving on to the
> next.
> Thoughts?
> Best,
> Mike S Craig
> (908) 328 8030
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>



More information about the Beginners mailing list