Lecture 15-1
map
map
applies a funciton f
to every element in a list.
map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' f (x:xs) = f x : map' f xs
This saves you from writing out the generic code for applying a function to a list. This allows you to implement the standard functions instead of having to make your own.
map even [1..5]
> [False,True,False,True,False]
This avoids writing a recursive function for applying simple list operations.
Currying and map
It is common to use curried functions with map
:
map (*2) [1..5]
> [2,4,6,8,10]
You can also use map to make other functions:
doubleList = map (*2)
> doubleList [1..5]
> [2,4,6,8,10]
Anonymous Functions and Map
It is also common to use an anonymous functions with map:
map (\x -> x * x) [1..5]
> [1, 4, 9, 16, 25]
This lets you apply your own functions to a list without having to define it.
Nested Maps
When working with nested lists, it is common to use nested maps.
map(map (*2)) [[1,2,3],[4,5,6],[7,8]]
> [[2,4,5],[8,10,12],[14,16]]
import Data.Char
map (map toUpper) ["the","quick","brown"]
["THE","QUICK","BROWN"]
This application uses currying in the inner map. It is also especially useful for lists containing strings.
Exercises
cubeList = map (^3)
middleElem = map (\ (_,x,_) -> x)
ruinStrings = map (map (\ x -> if x == 'e' then 'x' else x))