Calls a rule or function for each item in a list, passing the result of each call to the next one, and returns the value of the last computation.

**reduce**( *function*, *initial*, *list*, [*context*, … ])

*function*: (Rule or Function Reference) Rule or expression function.

*initial*: (Any Type) The accumulator's initial value.

*list*: (Any Type) Array of elements that the function iterates through.

*context*: (Any Type Array) Variable number of parameters passed directly into each function evaluation.

Any Type

Use `fn!functionName`

to reference an expression function and `rule!ruleName`

to reference a rule.

Best used when the computation of each operation needs to use the result from the previous operation such as when the result of each operation is an array that should be appended to each other in order. The result from the previous operation is then passed to the subsequent operation as the parameter initial.

The initial accumulator value is given by initial.

Null lists return a null list without executing the function.

Returns a scalar value if the function called returns a scalar, and returns a list if the function called returns a list.

To use rules or functions that take more than two arguments, use the merge() function.

- For example, given a rule
`g(x, y, z)`

,`reduce(rule!g, i, merge({a, b, c}, {d, e, f}))`

returns`g(g(g(i, a, d), b, e), c, f)`

.

You can experiment with this function in the test box below.

Test Input

Given a function `h(x, y)`

, `reduce(fn!h,initial, {a, b, c}, v)`

returns `h(h(h(initial, a, v), b, v), c, v)`

.

`reduce(fn!sum, 0, {1, 2, 3})`

returns `6`

Open in Github

On This Page