Scan
\ ⍀
|
Scan (\, ⍀) is a primitive monadic operator which takes a dyadic function operand and produces a monadic function which is equivalent to the reductions of the prefixes of the arguments. This operation is known as also known as cumulative reduction.
Explanation
Scan is similar to Reduce, however all the intermediate results will be retained. That being said, unlike Reduce, Scan does not reduce the rank of its argument, i.e. performing a scan over an N-dimensional array will produce an N-dimensional array.
Examples
+\⍳5 ⍝ plus-scan over range of integers from 1 to 5 1 3 6 10 15
Applications
Removing disconnected trailing 1s from a boolean mask:
mask←1 1 1 1 0 1 1 0 0 1
mask
1 1 1 1 0 1 1 0 0 1
∧\mask ⍝ and-scan mask
1 1 1 1 0 0 0 0 0 0
The scan +\ may be used to find parenthesis nesting level and ≠\ to mark quoted strings.
Ordering
Following APL's definition as a collection of reductions, the total number of function applications to evaluate Scan on a vector of length n is , specifically (n×n-1)÷2 or 2!n. Because of the use of right-to-left Reduce over prefixes of a vector, which extend from left to right, there is no way to combine these applications in general, so that many applications of Scan have quadratic complexity. If the wanted directions were the same (reduction on suffixes or left-to-right reduction on prefixes) then Scan could easily be defined to call the operand only n-1 times by reusing the result of each reduction. Because the two reduction orderings are equivalent for an associative operand, APL implementations frequently optimize using this form for common operands such as + and ≠.
Array languages K and Uiua, and APL dialect Kap, use a left-to-right reduction, which naturally gives linear evaluation on prefixes. dzaima/APL and BQN keep APL's right-to-left reduction but redefine Scan to evaluate linearly left to right. J defines operators to apply on prefixes and suffixes, so that the programmer can reduce on suffixes for linear evaluation, while TinyAPL provides both operators as well as a choice of left-to-right or right-to-left reduction, allowing linear scans in either direction.
External links
Lessons
Documentation