TExcelTAD
Home › Haskell › Haskell Folds & Scans

Haskell Folds & Scans

Many list functions have the same recursive shape: start with a value for the empty list, and combine each element with the result for the rest. sum, product, length, and, maximum and concat all look like that. A fold captures this shape once, so you only supply the two parts that differ: the combining function and the starting value.

haskell · try it yourself
main :: IO ()
main = do
  print (foldr (+) 0 [1, 2, 3, 4])       -- sum
  print (foldr (*) 1 [1, 2, 3, 4])       -- product
  print (foldr (&&) True [True, False])  -- and
  print (foldl (-) 100 [10, 20, 30])     -- ((100 - 10) - 20) - 30
  print (foldr (-) 100 [10, 20, 30])     -- 10 - (20 - (30 - 100))
10
24
False
40
-80

foldr and foldl

The two folds differ in which end they start from and how they bracket the operations:

text
foldr f z [a, b, c]  =  f a (f b (f c z))        -- a `f` (b `f` (c `f` z))
foldl f z [a, b, c]  =  f (f (f z a) b) c        -- ((z `f` a) `f` b) `f` c
foldr foldl / foldl'
Direction right to left (brackets nest to the right) left to right
Combining function \element acc -> … \acc element -> …
Works on infinite lists yes, if f can stop early no
Typical use building a new list, short-circuiting totals, counters, accumulators

For + and * the direction doesn't change the answer. For - it does, as the example shows. Note the argument order of the combining function: in foldr the element comes first, in foldl the accumulator comes first.

Writing functions with folds

haskell · try it yourself
myLength :: [a] -> Int
myLength = foldr (\_ acc -> acc + 1) 0

myReverse :: [a] -> [a]
myReverse = foldl (\acc x -> x : acc) []

myMap :: (a -> b) -> [a] -> [b]
myMap f = foldr (\x acc -> f x : acc) []

countVowels :: String -> Int
countVowels = foldr (\c n -> if c `elem` "aeiou" then n + 1 else n) 0

main :: IO ()
main = do
  print (myLength "folding")
  print (myReverse [1, 2, 3, 4])
  print (myMap (* 10) [1, 2, 3])
  print (countVowels "functional programming")
7
[4,3,2,1]
[10,20,30]
7

foldr with : naturally preserves order (it builds the list from the right), while foldl with : reverses it.

foldl': the one to use for totals

foldl is lazy: it builds a long chain of unevaluated additions before computing anything, which wastes memory on long lists. Data.List exports a strict version, foldl' (with an apostrophe), which evaluates the accumulator at every step. For sums, counts and other accumulations over big lists, use foldl':

haskell · try it yourself
import Data.List (foldl')

data Stats = Stats { count :: Int, total :: Int, largest :: Int }
  deriving Show

step :: Stats -> Int -> Stats
step (Stats c t m) x = Stats (c + 1) (t + x) (max m x)

main :: IO ()
main = do
  print (foldl' (+) 0 [1 .. 1000000])
  print (foldl' step (Stats 0 0 minBound) [7, 3, 12, 5])
500000500000
Stats {count = 4, total = 27, largest = 12}

The Stats record collects several results in one pass (records are covered later). The pattern "fold with a step function over a state" is how you write most loops in Haskell.

foldr1 and foldl1

When there is no sensible starting value, as for a maximum, foldr1 and foldl1 use the first element instead. They crash on an empty list, so use them only when the list is known to be non-empty:

haskell · try it yourself
main :: IO ()
main = do
  print (foldr1 max [3, 9, 2, 7])
  print (foldl1 (\a b -> a * 10 + b) [2, 0, 2, 6])
  print (foldr1 (\w acc -> w ++ ", " ++ acc) ["red", "green", "blue"])
9
2026
"red, green, blue"

Scans: every intermediate result

A scan is a fold that keeps all the intermediate accumulator values. It is perfect for running totals:

haskell · try it yourself
main :: IO ()
main = do
  let deposits = [100, -20, 50, -80, 30]
  print (scanl (+) 0 deposits)          -- balance after each transaction
  print (scanl1 (+) deposits)            -- same, starting from the first element
  print (scanr (+) 0 [1, 2, 3])          -- totals from the right
  print (scanl1 max [3, 1, 4, 1, 5, 9, 2])  -- best value so far
  print (takeWhile (< 100) (scanl1 (+) [1 ..]))   -- triangular numbers below 100
[0,100,80,130,50,80]
[100,80,130,50,80]
[6,5,3,0]
[3,3,4,4,5,9,9]
[1,3,6,10,15,21,28,36,45,55,66,78,91]

scanl f z xs always has one more element than xs (it starts with z), and its last element is foldl f z xs.

Folding with foldr and laziness

Because foldr hands the combining function the rest of the computation lazily, a function that doesn't need the rest can stop early, even on an infinite list:

haskell · try it yourself
anyBig :: [Int] -> Bool
anyBig = foldr (\x rest -> x > 1000 || rest) False

main :: IO ()
main = do
  print (anyBig [5, 50, 5000, 2])
  print (anyBig [1 ..])                 -- stops at 1001
  print (take 5 (foldr (\x acc -> x * 2 : acc) [] [1 ..]))
True
True
[2,4,6,8,10]

|| only looks at rest when x > 1000 is False, so the fold stops as soon as it finds a big number.

Tip: A rule of thumb: use foldr to build lists or when you may stop early, foldl' to compute a single accumulated value, and avoid plain foldl.

Test yourself

What is foldr (\x acc -> x : acc) [] [1, 2, 3]?

  1. [3,2,1]
  2. [1,2,3]
  3. 6
  4. []

What is scanl (+) 0 [1, 2, 3]?

  1. [1,3,6]
  2. [0,1,3,6]
  3. 6
  4. [6,5,3,0]

Which fold should you use to sum a list of a million numbers?

  1. foldl
  2. foldl'
  3. foldr1
  4. scanr