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, \ldots, xn\}) is equivalent to fold(f, x0, \{x1, \ldots, 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, \ldots, x_n\}, f) returns f...f(f(x_{n-2}, f(x_{n-1}, x_n))). That is, f is applied to the last two elements of the list first, then the repeated calls to f proceed backwards through the list. The optional argument x in fold(L, x, f) is used as the second argument in the first evaluation of f. So fold(\{x_0, x_1, \ldots, x_{n-1}\}, x_n, f) is equivalent to fold(\{x_0, x_1, \ldots, x_n\}, f).
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 |
The object fold is a method function.