November 2015
Intermediate to advanced
166 pages
3h 14m
English
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' ...Read now
Unlock full access