Fold · functional programming

Also known as: reduce

On this page 7

A fold in functional programming is a higher-order function that reduces a data structure to a single value by repeatedly applying a combining function to an accumulator and each element in turn. Also known as reduce, and in some languages as accumulate, aggregate or inject, it captures the general pattern of structural recursion over lists, trees and other containers.

Many familiar operations, including sum, product, length, maximum, map and filter, can be written as a fold, which is why the fold is often described as the universal iterator of functional programming.

How a fold processes a collection

A fold takes three inputs: a combining function, an initial accumulator value and the collection itself. It starts with the initial value, combines it with the first element, passes the result forward as the new accumulator and repeats until the elements are exhausted. The final accumulator is the result.

Conceptually, a fold replaces the constructors of a data structure with other operations. A list built as 1 : 2 : 3 : [] becomes 1 + (2 + (3 + 0)) when the cons operator is replaced with addition and the empty list with zero. This view explains why folds generalize to trees and other algebraic data types, where each constructor receives its own replacement function.

The table below traces a left fold that sums the list [3, 5, 7] starting from an accumulator of 0.

StepAccumulator beforeElementAccumulator after
Start0None0
Step 1033
Step 2358
Step 38715
Result15None15
Step-by-step trace of a left fold computing a sum

Left fold versus right fold

The two basic variants differ in association order: a left fold groups operations from the first element, ((z ⊕ a) ⊕ b) ⊕ c, while a right fold groups them from the last, a ⊕ (b ⊕ (c ⊕ z)). For associative operations with a neutral element, both give the same answer, but for subtraction, string building or list construction the results differ.

PropertyLeft fold (foldl)Right fold (foldr)
GroupingFrom the leftFrom the right
Function signature(acc, element) to acc(element, acc) to acc
Tail recursiveYesNo in strict languages
Works on infinite listsNoYes with lazy evaluation and a lazy operator
Preserves list order when rebuildingReverses unless adjustedPreserves order
Typical useSums, counters, strict aggregationMap, filter, short-circuit logic
Characteristics of left and right folds

In Haskell, laziness makes the choice subtle. The lazy foldl builds a long chain of unevaluated thunks and can exhaust memory on large lists, so practitioners use the strict variant foldl’ for numeric aggregation. Conversely, foldr can stop early on infinite lists when the combining function does not need the accumulator, as in checking whether any element satisfies a predicate.

Fold variants across languages

Most modern languages provide folds under different names and with different defaults, which matters when porting code. The next table lists representative forms.

LanguageFunctionDirectionInitial value
Haskellfoldl’, foldr, foldMapLeft and rightRequired, except foldl1 and foldr1
ScalafoldLeft, foldRight, reduceLeft and rightRequired for fold, absent for reduce
JavaScriptArray.prototype.reduceLeftOptional
Pythonfunctools.reduceLeftOptional
RustIterator::foldLeftRequired
F#List.fold, List.foldBackLeft and rightRequired
Fold functions in common languages

A common distinction separates fold, which takes an explicit seed, from reduce, which uses the first element as the seed. Reduce fails or returns an empty option on an empty collection, while a fold with a seed always produces a value, which makes it the safer default when emptiness is possible.

Folds, monoids and parallel aggregation

When the combining function is associative and the seed is its identity element, the pair forms a monoid, and the fold gains a powerful property: the collection can be split into chunks, each chunk folded independently and the partial results combined in any grouping. This is the mathematical basis of parallel reduction in frameworks such as MapReduce and of tree-shaped reductions on GPUs.

Haskell’s foldMap expresses this directly by mapping each element into a monoid and combining the results. Examples of valid monoids include addition with 0, multiplication with 1, string concatenation with the empty string and the maximum operation with negative infinity. A non-associative operation such as subtraction or floating-point summation, which is only approximately associative, can yield different results when the reduction order changes.

Common mistakes when using fold

Most fold errors come from a wrong seed, a wrong direction or an inefficient accumulator. The following table summarizes frequent symptoms and their corrections.

SymptomCauseFix
Product always equals zeroSeed of 0 for multiplicationUse the identity element 1
Stack overflow on large inputNon-tail-recursive right fold in a strict languageUse a left fold
Memory growth in HaskellLazy foldl accumulating thunksUse foldl’ or strict data
Quadratic running timeAppending to the end of an immutable listPrepend and reverse once
Error on empty inputReduce without a seedUse fold with an explicit seed
Fold mistakes, causes and fixes

Readability is another concern. A fold with a complex tuple accumulator that tracks several values at once can be harder to follow than two simple passes or a named helper function, so experienced developers keep the combining function small and well named.

A plain-language summary

A fold works like adding up a shopping receipt line by line. You start with a running total of zero. You add the price of the first item. Then you carry the new total to the next line, until the last line gives the final amount.

The same pattern can do much more than add numbers. Change the rule used at each step, and a fold can count items or find the most expensive one. It turns many separate loops into one idea.

An example from practice

An analytics team processes about 50 million order events per day and needs the total revenue, order count and largest order for each region. Instead of writing three separate loops, a Scala developer defines a small summary record and a combining function that merges one event into a summary.

Because merging two summaries is associative and an empty summary acts as the identity, the same combining logic runs as a fold within each data partition and then combines the partial summaries across a Spark cluster. The developer only had to write and test one function.

The job reads each event once instead of three times, and the nightly run completes in roughly a third of the earlier time. When finance later asked for the average order value, the team added one field to the summary record without restructuring the pipeline.