scan
Module Export
[value] scan (acc, item) => expression |> [value][value] scan initial using (acc, item) => expression |> [value]Accumulates values over an iterator, yielding each intermediate accumulator value.
The scan function processes an iterator by applying an accumulator function to each item, yielding every intermediate accumulator value.
There are two forms:
- Without an initial value: the first item of the iterator becomes the initial accumulator, and the function is called starting from the second item onward. This is sometimes called
scanl1in other functional languages. - With an initial value: the initial value is prepended to the output and used as the starting accumulator. The function is called for every item of the iterator. This is sometimes called
scanlin other functional languages.
Unlike
reduce, where the initial value acts as a fallback/seed that is not part of the output, the initial value inscanis always emitted as the first element of the resulting iterator.
Examples
Running sum
import 'iterators'
from [1, 2, 3, 4] scan (acc, item) => acc + itemResult:
[1, 3, 6, 10]Running sum with an initial value
import 'iterators'
from [1, 2, 3, 4] scan 0 using (acc, item) => acc + itemResult:
[0, 1, 3, 6, 10]Running product
import 'iterators'
from [1, 2, 3, 4] scan (acc, item) => acc * itemResult:
[1, 2, 6, 24]Single element
If the iterator has a single element, the function is never called and that element is returned as-is:
import 'iterators'
from [42] scan (acc, item) => acc + itemResult:
[42]Empty iterator
Scanning an empty iterator produces an empty iterator:
import 'iterators'
let numbers: [number] = []from numbers scan (acc, item) => acc + itemResult:
[]Empty iterator with an initial value
When an initial value is provided, scanning an empty iterator yields just the initial value:
import 'iterators'
let numbers: [number] = []from numbers scan 99 using (acc, item) => acc + itemResult:
[99]Combined with other macros
import 'iterators'
from [1, 2, 3] scan (acc, item) => acc + item lastResult:
6