🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Folds

A fold is a function that combines the values in a list into one value, beginning with a starting value. The foldl function works from the left and the foldr function works from the right.

foldl adds a list from the left

Starting from 0, the fold adds 1, then 2, then 3, then 4.

main :: IO ()
main = print (foldl (+) 0 [1, 2, 3, 4])

foldr multiplies a list from the right

Starting from 1, the fold multiplies by 4, then 3, then 2.

main :: IO ()
main = print (foldr (*) 1 [2, 3, 4])

Subtraction shows the fold direction

The two results are foldl (-) 0 [1, 2, 3] and then foldr (-) 0 [1, 2, 3], in that order.

main :: IO ()
main = print (foldl (-) 0 [1, 2, 3], foldr (-) 0 [1, 2, 3])

Example

main :: IO ()
main = print (foldl (+) 50 [10, 20, 30])

Key points

  • Starting value: a fold begins combining from the starting value passed to it.
  • Foldl function: foldl combines the values in a list from left to right.
  • Foldr function: foldr combines the values in a list from right to left.
  • Parentheses: an operator such as (+) or (*) is written in parentheses when it is passed as a function.
  • Matching results: folds with (+) and (*) give the same result from either direction.
  • Order matters: with subtraction, the left fold and the right fold give different results because subtraction depends on order.

In this example, the fold starts at 50 rather than 0. It adds 10 to make 60, then 20 to make 80, then 30 to make 110, and print shows that final value.

Note

foldl is read as fold left and foldr is read as fold right.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is the value of foldr (-) 0 [1, 2, 3]?