# accumulate -- apply a binary operator repeatedly

## Synopsis

• Usage:
accumulate(f, x, L)
accumulate(f, L)
accumulate(L, x, f)
accumulate(L, f)
• Inputs:
• f,
• x,
• L,
• Outputs:

## Description

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

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 : fold({2,3,2,1}, 2, (x,y) -> x^y) o9 = 512

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

## Ways to use accumulate :

• "accumulate(Function,Thing,VisibleList)"
• "accumulate(Function,VisibleList)"
• "accumulate(VisibleList,Function)"
• "accumulate(VisibleList,Thing,Function)"

## For the programmer

The object accumulate is .