🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Map and Filter

Map and filter are functions that build a new list from an existing list. Map changes every value, while filter keeps only the values that pass a test.

Map changes every value

The lambda multiplies each number by three.

main :: IO ()
main = print (map (\x -> x * 3) [1, 2, 3, 4])

Filter keeps only passing values

The lambda tests each number, and only the numbers above five stay.

main :: IO ()
main = print (filter (\x -> x > 5) [3, 8, 5, 9])

Named functions work with map and filter too

The first list is map with the named function double, and the second list is filter with the named test big.

double x = x * 2
big x = x > 10

main :: IO ()
main = print (map double [1, 2, 3], filter big [5, 15, 25])

Example

main :: IO ()
main = print (map (\x -> x + 100) (filter (\x -> x >= 50) [40, 50, 60, 70]))

Key points

  • Map function: map applies a function to every value in a list.
  • Filter function: filter keeps each value for which its test returns True.
  • New list: map and filter each return a new list and leave the original list unchanged.
  • Lambda use: a lambda can give the change or the test inline, where map or filter needs it.
  • Named function: a function defined with a name can also be passed to map or filter.
  • Result order: the values in the new list stay in the same order as in the original list.

In this example, filter first keeps the numbers that are at least 50, giving [50, 60, 70]. Map then adds 100 to each of those numbers, so print shows [150,160,170].

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is the value of filter (\x -> x < 4) [1, 5, 3, 6]?