Fold

Fold[f,x,list]

gives the last element of FoldList[f,x,list].

Fold[f,list]

is equivalent to Fold[f,First[list],Rest[list]].

Fold[f]

represents an operator form of Fold that can be applied to expressions.

Details

• You can use Throw to exit from Fold before it is finished.
• Fold[f][list] is equivalent to Fold[f,list].
• Fold[f][x,list] is equivalent to Fold[f,x,list].

Examples

open allclose all

Basic Examples(7)

Start from the first element of the list:

Use the operator form of Fold on one argument:

Use the operator form of Fold on two arguments:

Scope(2)

Perform two subsequent permutations:

Perform a chain of cross products:

Generalizations & Extensions(3)

The head need not be List:

Use Throw to exit a Fold:

Fold to the right:

Applications(9)

Create a nested polynomial (Horner form):

HornerForm directly produces this output:

Form a continued fraction:

Form a number from digits:

Form an alternating sum:

Form a binary tree:

Form a left-branching binary tree:

Form a function composition:

Apply an indexed sequence of functions:

Successively partition a list:

Properties & Relations(3)

Folding with an empty list does not apply the function at all:

Fold returns the last element of FoldList:

Functions that ignore their second argument give the same result as in Nest:

Possible Issues(1)

An empty list cannot be folded:

However, the action of FoldList is well defined:

Neat Examples(3)

An explicit form of the primitive recursive function r[z,r[s,r[s,r[s,p[2]]]]] [more info]:

Generate all subsets of a set:

Find all possible sums of any of the elements of a list of numbers:

The fourth SwinnertonDyer polynomial [more info]:

Wolfram Research (1991), Fold, Wolfram Language function, https://reference.wolfram.com/language/ref/Fold.html (updated 2016).

Text

Wolfram Research (1991), Fold, Wolfram Language function, https://reference.wolfram.com/language/ref/Fold.html (updated 2016).

BibTeX

@misc{reference.wolfram_2021_fold, author="Wolfram Research", title="{Fold}", year="2016", howpublished="\url{https://reference.wolfram.com/language/ref/Fold.html}", note=[Accessed: 21-June-2021 ]}

BibLaTeX

@online{reference.wolfram_2021_fold, organization={Wolfram Research}, title={Fold}, year={2016}, url={https://reference.wolfram.com/language/ref/Fold.html}, note=[Accessed: 21-June-2021 ]}

CMS

Wolfram Language. 1991. "Fold." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2016. https://reference.wolfram.com/language/ref/Fold.html.

APA

Wolfram Language. (1991). Fold. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Fold.html