Skip to content

scan

Module Export

[value] scan (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. The first item becomes the initial accumulator, and the function is called starting from the second item onward.

This is sometimes called scanl1 in other functional languages.

Examples

Running sum

import 'iterators'
from [1, 2, 3, 4] scan (acc, item) => acc + item

Result:

[1, 3, 6, 10]

Running product

import 'iterators'
from [1, 2, 3, 4] scan (acc, item) => acc * item

Result:

[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 + item

Result:

[42]

Empty iterator

Scanning an empty iterator produces an empty iterator:

import 'iterators'
let numbers: [number] = []
from numbers scan (acc, item) => acc + item

Result:

[]

Combined with other macros

import 'iterators'
from
[1, 2, 3]
scan (acc, item) => acc + item
last

Result:

6