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 interations. Lifecycle of a fold:

  1. Call fn(foldStart, null), return initial accumulator state
  2. Call fn(item, acc) for every item, return new accumulator state
  3. 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:


[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}

Also see reduce() which is easier to use if doing your own simple rollup computation.




Feature namespace of definitions formatted as feature:name


Axon function