Skip to content

foldl' and foldr'

These are strict versions of foldl and foldr. Remember, lazy evaluation means that we build up potentially large expressions before finally evaluating them when we need to know the value of the expression. If we fold up a list using foldl (+) 0 [1..1000000], then this builds the massive expression (((0 + 1) + 2) + ... + 1000000) and evaluates it only once we ask for its value.

The expression foldl' (+) 0 [1..1000000] behaves differently. It immediately evaluates the subexpression 0 + 1 to obtain the value 1. Then it evaluates the expression 1 + 2 to obtain the value 3. Then it evaluates 3 + 3 to obtain 6. And so on until it adds the final number, 1000000 to the sum. At any given point during the evaluation, all we have is a number. Thus, this takes constant space, whereas the expression foldl (+) 0 [1..1000000] would use linear space to store the whole expression (((0 + 1) + 2) + ... + 1000000) before evaluating it.

The difference between foldr and foldr' is the same.