Skip to content
Map, Filter, Fold
step 1/5

Reading — step 1 of 5

Learn

~1 min readLists and Beyond

The functional toolkit. Most Haskell loops boil down to these three:

map :: (a -> b) -> [a] -> [b]
map (* 2) [1, 2, 3]              -- [2, 4, 6]

filter :: (a -> Bool) -> [a] -> [a]
filter even [1, 2, 3, 4]         -- [2, 4]

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr (+) 0 [1, 2, 3]            -- 6
foldr max 0 [3, 1, 4, 1, 5]      -- 5

foldr builds the result from the right:

foldr f z [a, b, c] = f a (f b (f c z))

There's also foldl (from the left) and the strict foldl' (from Data.List) which avoids stack overflow on big lists. Prefer foldl' over foldl for numeric folds.

Compose them in pipelines:

sumOfSquaresOfEvens xs = sum (map (^ 2) (filter even xs))
-- or with $:
sumOfSquaresOfEvens xs = sum $ map (^ 2) $ filter even xs

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…