[Haskell-cafe] Composing monads (sort of)

Chris Eidhof chris at eidhof.nl
Sat Dec 16 09:35:41 EST 2006

Hey Mark,

> How can I concisely compose these functions without having to write  
> a cascade of case statements such as:
> case f1 rec1 of
>     Nothing -> return Nothing
>     Just id1 -> do
>                     rec2 <- f2 id2
>                     return $ case rec2 of
>                                 Nothing -> return Nothing
>                                 Just rec2' -> case f3 rec2' of
>                                                 ....
> I understand that if I was just dealing with Maybe I could use the  
> fact that Maybe is a monad.
Yes, you can write like this:

> id2 <- f1 rec1
> rec2 <- f2 id2
> rec3 <- f3 rec2
> return rec3
or, even shorter:
> id2 <- f1 rec1
> rec2 <- f2 id2
> f3 rec2

The cool thing of the Maybe monad is that it combines a result in  
such a way that it removes the plumbing of constantly checking for  
Nothing. I can definitely recommand you the following tutorials:


Those two tutorials really helped me.

Good luck,

More information about the Haskell-Cafe mailing list