Mapping over lists

The map function is a specialization of fold since we can write map in terms of fold:

  map f = foldr ((:).f) []

Just as with fold, we can map over lists with regular or monadic functions:

doF n = do print n; return (n * 2)
main = do
    print $ map (* 2) [2, 3, 5, 7]
    mapM  doF [2, 3, 5, 7] >>= print
    mapM_ doF [2, 3, 5, 7]

The type signatures are very informative:

   map   :: (a -> b)   -> [a] -> [b]
   mapM  :: (a -> m b) -> [a] -> m [b]
   mapM_ :: (a -> m b) -> [a] -> m ()

In Chapter 3, Patterns of Composition, we wrote mapM in terms of sequence and sequenceA (the Monad and Applicative forms respectively). When we use sequenceA, we get a function that maps over Applicative:

  mapA :: Applicative f => (a -> f t) -> [a] -> f [t] mapA f = sequenceA' ...

Get Haskell Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.