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

Michael Craig mkscrg at gmail.com
Thu Sep 15 00:48:29 CEST 2011


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110914/97eef322/attachment.htm>


More information about the Beginners mailing list