Algosim documentation: accumulate

accumulate

Computes a value by accumulating the values in a container.

Syntax

Description

If X is an ordered container, x a value, and f a function, then accumulate(X, x, f) returns the value obtained by accumulating the values in X using x as the initial value and f as the function. Specifically, the following values are computed:

x[0] ≔ x
x[1] ≔ f(x[0], X[1])
x[2] ≔ f(x[1], X[2]),
⋮
x[n] ≔ f(x[n−1], X[n])

where n = #X. accumulate(X, x, f) then returns x[n].

Examples

X ≔ ❨5, 1, 2, −6, 4, 2, 1, 1, −6❩
(5, 1, 2, −6, 4, 2, 1, 1, −6)
accumulate(X, 0, add)
4
accumulate(X, 1, multiply)
2880
accumulate(X, 0, max)
5
accumulate(X, 0, min)
−6
accumulate(X, 1, lcm)
60
accumulate(X, 1, (a, b) ↦ 2⋅a − 3⋅b)
−3760

Note: In all examples but the last one, it is better to use the dedicated function: sum, product, max, min, lcm.

See also