How to read mapM

June 14, 2011, Tags: monad, haskell

How to understand the following computation result?

Prelude> mapM id [Just 1, Nothing, Just 3]
Nothing

‘Reason about’

mapM     :: (a -> m b) -> [a] -> m [b]
id       :: a -> a
sequence :: (Monad m) => [m a] -> m [a]

Therefore,

> a = Maybe Int
> m = Maybe
> b = Int

the mapM and sequence is implemented like this:

mapM f xs = sequence (map f xs)

sequence (c:cs) = do x  <- c
                     xs <- sequence cs
                  return (x:xs)

Hence the result could be understood in such way

  mapM id [Just 1, Nothing, Just 3]
= sequence (map id [Just 1, Nothing, Just 3])
= sequence [Just 1, Nothing, Just 3]
= do { x <- Just 1; xs <- sequence [Nothing, Just 3]; return (x:xs) }
= ...
= Just 1 >>= \x -> Nothing >>= \y -> Just 3 >>= \z -> return (x:y:z)
= Nothing          -- Because Nothing >>= ... produce Nothing