Skip to content

Scan ​

The running combination of ff over a collection, one result per element.

Scan(xs, f)[f(x1),f(f(x1),x2),…][f(x_1), f(f(x_1), x_2), \ldots] — same length as xsxs, the partial folds of ff with no seed.
Scan(xs, f, init)as above, but folding from initinit — still same length as xsxs (the seed is not itself an output element).
Typed signatures
TypePackageApplies
(indexed_collection<T>, reducer: (unknown, T) any -> unknown, initial: value?) -> indexed_collection where Tcompute-enginealways

Domain: Collections

Examples

Basic #
live ↗
InScan([1,2,3,4],Add)\mathrm{Scan}(\bigl\lbrack1, 2, 3, 4\bigr\rbrack, \mathrm{Add})Out[1,3,6,10]\bigl\lbrack1, 3, 6, 10\bigr\rbrack

The shape of a running fold

live ↗
InScan([a,b,c],f)\mathrm{Scan}(\bigl\lbrack a, b, c\bigr\rbrack, f)Out[a,f(a,b),f(f(a,b),c)]\bigl\lbrack a, f(a, b), f(f(a, b), c)\bigr\rbrack
Scope #

The running maximum

live ↗
InScan([1,2,3,4],Max)\mathrm{Scan}(\bigl\lbrack1, 2, 3, 4\bigr\rbrack, \mathrm{Max})Out[1,2,3,4]\bigl\lbrack1, 2, 3, 4\bigr\rbrack

Running products: the factorials

live ↗
InScan([1,2,3,4,5],Multiply)\mathrm{Scan}(\bigl\lbrack1, 2, 3, 4, 5\bigr\rbrack, \mathrm{Multiply})Out[1,2,6,24,120]\bigl\lbrack1, 2, 6, 24, 120\bigr\rbrack

Running sums of symbolic elements -- Wolfram's Accumulate

live ↗
InScan([a,b,c],Add)\mathrm{Scan}(\bigl\lbrack a, b, c\bigr\rbrack, \mathrm{Add})Out[a,a+b,a+b+c]\bigl\lbrack a, a+b, a+b+c\bigr\rbrack

The running minimum

live ↗
InScan([3,1,4,1,5],Min)\mathrm{Scan}(\bigl\lbrack3, 1, 4, 1, 5\bigr\rbrack, \mathrm{Min})Out[3,1,1,1,1]\bigl\lbrack3, 1, 1, 1, 1\bigr\rbrack

An empty list scans to an empty list

live ↗
InScan([],Add)\mathrm{Scan}(\bigl\lbrack\bigr\rbrack, \mathrm{Add})Out[]\bigl\lbrack\bigr\rbrack
Applications #

The values of every prefix of the binary digits 1011

live ↗
InScan([1,0,1,1],(_1⁡,_2⁡)↦2_1⁡+_2⁡)\mathrm{Scan}(\bigl\lbrack1, 0, 1, 1\bigr\rbrack, (\operatorname{\_1}, \operatorname{\_2})↦2\operatorname{\_1}+\operatorname{\_2})Out[1,2,5,11]\bigl\lbrack1, 2, 5, 11\bigr\rbrack
Possible issues #

The seeded form is still the same length as xsxs — the seed isn't an output element

live ↗
InScan([1,2,3],Add,10)\mathrm{Scan}(\bigl\lbrack1, 2, 3\bigr\rbrack, \mathrm{Add}, 10)Out[11,13,16]\bigl\lbrack11, 13, 16\bigr\rbrack
About
Examples9
Checked againstWolfram Language 8 agree1 differ

See also: Fold