Macaulay2Doc :: fold

- Usage:
`fold(f, x, L)``fold(f, L)``fold(L, x, f)``fold(L, f)`

- Inputs:
`f`, a function`x`, a thing`L`, a visible list

- Outputs:
`M`, a list

Suppose `L={x0, x1, ..., xn}`. Then for any binary operator `f`, `fold(f, L)` computes `f(...f(f(x0, x1), x2), ...)`. In other words, the binary operator is applied to the first two elements of `L`, then to that result along with the next unused element of `L`, and so forth.

i1 : fold(plus, {0,1,2,3,4,5}) o1 = 15 |

i2 : fold(identity, {a,b,c,d,e}) o2 = ((((a, b), c), d), e) o2 : Sequence |

i3 : fold((i,j) -> i|j|i, {"a","b","c","d","e"}) o3 = abacabadabacabaeabacabadabacaba |

If `fold(f, x, L)` is called, the element `x` is used as the first argument of the binary function `f`. In other words, `fold(f, {x0, x1, ..., xn})` is equivalent to `fold(f, x0, {x1, ..., xn})`.

i4 : fold(plus, 0, {1,2,3,4,5}) o4 = 15 |

i5 : fold((x, y) -> x^y, 2, {3,2,1,2}) o5 = 4096 |

The function `fold({x _{0}, x_{1}, ..., x_{n}}, f)` returns

i6 : fold({a,b,c,d,e}, identity) o6 = (a, (b, (c, (d, e)))) o6 : Sequence |

i7 : fold({a,b,c,d}, e, identity) o7 = (a, (b, (c, (d, e)))) o7 : Sequence |

i8 : fold({2,3,2,1}, 2, (x, y) -> x^y) o8 = 512 |

The difference between fold and `accumulate` is that `fold` returns the final result of all the nested evaluations of `f`, while `accumulate` lists all the intermediate values as well.

i9 : accumulate({2,3,2,1}, 2, (x, y) -> x^y) o9 = {512, 9, 2, 1} o9 : List |

- apply -- apply a function to each element
- accumulate -- apply a binary operator repeatedly
- lists and sequences -- a detailed overview of lists and sequences in Macaulay2

- fold(Function,Thing,VisibleList)
- fold(Function,VisibleList)
- fold(VisibleList,Function)
- fold(VisibleList,Thing,Function)