O'Reilly logo

Haskell Design Patterns by Ryan Lemmer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required