typestar

map & filter in Haskell

map rewrites every element, filter keeps the ones that pass, and (.) chains the two into a pipeline.

-- map applies a named function to every element, one at a time
restock :: Int -> Int
restock n = n + 12

-- a section is a half-applied operator: (< 5) still wants a left side
lowStock :: [Int] -> [Int]
lowStock = filter (< 5)

-- (.) chains them: filter runs first, then map, reading right to left
topUp :: [Int] -> [Int]
topUp = map restock . lowStock

main :: IO ()
main = do
  let shelf = [2, 8, 4, 11, 1] :: [Int]
  print (map (* 2) shelf)
  print (lowStock shelf)
  print (topUp shelf)

How it works

  1. map restock hands each element to the named restock, which adds 12 to it.
  2. lowStock = filter (< 5) uses a section: an operator with one side already supplied, still waiting for the other.
  3. topUp = map restock . lowStock filters before it maps, and main also applies the inline section map (* 2).

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
484
Tokens
89
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 1 of 3 in Higher-order, step 13 of 27 in Language basics.

← Previous Next →

map & filter in other languages