UP | HOME

MapM

1. How to understand the following computation result?

mapM id [Just 1, Nothing, Just 3]

2. 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