def
func:fold
fold(val, fn)
Fold a list or stream into a single value using given folding function. The folding function signature must be (val, acc)
where val is the items being folded, and acc is an accumulator used to maintain state between iterations. Lifecycle of a fold:
- Call
fn(foldStart, null)
, return initial accumulator state - Call
fn(item, acc)
for every item, return new accumulator state - Call
fn(foldEnd, acc)
return final result
See Streams for streaming details.
The fold will short-circuit and halt immediately if the folding function returns na()
for the accumulator state. The result of the fold is na()
in this case. A folding function should document its behavior when a collection contains na()
.
Built-in folding functions include:
count()
sum()
avg()
min()
max()
mean()
median()
rootMeanSquareErr()
meanBiasErr()
standardDeviation()
Examples:
[1, 2, 3, 4].fold(max) // fold list into its max value [1, 2, 3, 4].fold(avg) // fold list into its average value [1, 2, na(), 3].fold(sum) // => na()
Example of writing your own custom fold function that used start/end values and has support for na():
average: (val, acc) => do if (val == foldStart()) return {sum:0, count:0} if (val == foldEnd()) return acc->sum / acc->count if (val == na()) return na() return {sum: acc->sum + val, count: acc->count + 1} end
Also see reduce()
which is easier to use if doing your own simple rollup computation.