# 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(4)

Successively apply a function f to a seed x and the elements of a list:

Use Fold with List to create nested ordered pairs:

Multiply elements one element at a time:

Start from the first element of the list:

## Scope(8)

Use a pure function with Fold:

Use the operator form of Fold on one argument:

Use the operator form of Fold on two arguments:

Created nested powers with left-associativity:

Created nested powers with right-associativity:

Perform two subsequent permutations:

Perform a chain of cross products:

The head of the third argument need not be List:

Use Throw to exit a Fold early:

## 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(9)

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

Equivalently, this does not apply the function at all:

Fold returns the last element of FoldList:

Fold requires a function f that takes the seed in its first argument:

To use the seed in the second argument, use ReverseApplied:

Fold takes list elements from left to right:

Use Reverse to take elements from right to left:

Combine Reverse and ReverseApplied:

Folding an additional element is equivalent to applying the function to the additional element:

Fold[f,x,{a,b,}] is equivalent to Fold[f,f[x,a],{b,}]:

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

FoldList can be computed with NestWhileList:

Fold[Append,{},list] is equivalent to list:

## Possible Issues(1)

An empty list cannot be folded without a seed:

However, the action of FoldList is well defined: