Macaulay2 » Documentation
Packages » Macaulay2Doc :: accumulate
next | previous | forward | backward | up | index | toc

accumulate -- apply a binary operator repeatedly



Suppose L=\{x0, x1, ..., xn\}. Then for any binary operator f, accumulate(f, L) returns the list \{f(x0, x1), 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 : accumulate(plus, {0,1,2,3,4,5})

o1 = {1, 3, 6, 10, 15}

o1 : List
i2 : accumulate(concatenate, {a,b,c,d,e})

o2 = {ab, abc, abcd, abcde}

o2 : List
i3 : accumulate((i,j) -> i|j|i, {"a","b","c","d","e"})

o3 = {aba, abacaba, abacabadabacaba, abacabadabacabaeabacabadabacaba}

o3 : List

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

i4 : accumulate(plus, 0, {1,2,3,4,5})

o4 = {1, 3, 6, 10, 15}

o4 : List
i5 : accumulate((x, y) -> x^y, 2, {3,2,1,2})

o5 = {8, 64, 64, 4096}

o5 : List

The function accumulate(\{x_0, x_1, \ldots, x_n\}, f) returns the list \{..., f(x_{n-2}, f(x_{n-1}, x_n)), f(x_{n-1}, x_n) \} . That is, f is applied to the last two elements of the list, and the result placed at the end of the output. Then the accumulation proceeds backwards through the list. The optional argument x in accumulate(L, x, f) is used as the second argument in the first evaluation of f. So accumulate(\{x_0, x_1, \ldots, x_{n-1}\}, x_n, f) is equivalent to accumulate(\{x_0, x_1, \ldots, x_n\}, f).

i6 : accumulate({a,b,c,d,e}, concatenate)

o6 = {abcde, bcde, cde, de}

o6 : List
i7 : accumulate({a,b,c,d}, e, concatenate)

o7 = {abcde, bcde, cde, de}

o7 : List
i8 : accumulate({2,3,2,1}, 2, (x, y) -> x^y)

o8 = {512, 9, 2, 1}

o8 : List

If L is an instance of class the the iterator method installed, e.g., a string, then it may also be used with accumulate, but only the versions with f as the first argument. Its return value in this case is an Iterator object.

i9 : iter = accumulate(identity, "abcde")

o9 = iterator iterator "abcde"

o9 : Iterator
i10 : next iter

o10 = (a, b)

o10 : Sequence
i11 : next iter

o11 = ((a, b), c)

o11 : Sequence
i12 : next iter

o12 = (((a, b), c), d)

o12 : Sequence

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.

i13 : fold({2,3,2,1}, 2, (x,y) -> x^y)

o13 = 512

See also

Ways to use accumulate :

For the programmer

The object accumulate is a method function.