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
map restockhands each element to the namedrestock, which adds 12 to it.lowStock = filter (< 5)uses a section: an operator with one side already supplied, still waiting for the other.topUp = map restock . lowStockfilters before it maps, andmainalso applies the inline sectionmap (* 2).
Keywords and builtins used here
IOIntdoletlowStockmainrestocktopUp
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.
Step 1 of 3 in Higher-order, step 13 of 27 in Language basics.