Reduce and Scan#
An operator takes 1 or 2 operands (which are usually functions) as arguments, and derives a function which itself can either be monadic or dyadic.
/
(reduce) is a monadic operator which derives an ambivalent function. ambivalent meaning that it can be used both monadically and dyadically. It is called reduce because it always reduces the rank of its argument by 1.
Reduction on a vector is straightforward; F/a b c d e...
is equivalent to ⊂a F b F c F d F e...
. The result of a reduction will have the shape of the argument excluding the last axis.
+/3 1 4 1 5
3 + 1 + 4 + 1 + 5
×/(1 2 3)(4 5 6)(7 8 9) ⍝ The result is enclosed, because the rank must be 0
Since functions in APL are right-associative, this has an effect on reduce. For example -/
is alternating sum.
-/1 2 3 4
1-2-3-4
For higher rank arrays reduce will reduce along the last axis.
3 4⍴⍳12
+/3 4⍴⍳12
The twin of /
, ⌿
reduces along the first axis, i.e the columns of a matrix.
+⌿3 4⍴⍳12
If you need to reduce across some other axis, like the second in a rank-3 array, you can use f/[axis]
. f/[1]
is the same as f⌿
.
2 3 4⍴⍳24
(+⌿2 3 4⍴⍳24)(+/[2]2 3 4⍴⍳24)(+/2 3 4⍴⍳24)
As a dyadic function, L f/ R
is a windowed reduction, i.e the f
-reduction of each sliding window of size L in R.
2 +/3 1 4 1 5
3 +/ 3 1 4 1 5
Windowed reduction does not change the rank.
2 +/ 3 4⍴⍳12
2 +⌿ 3 4⍴⍳12
If the left argument is negative, the windows are reversed.
¯2 -/ 0 1 3 6 10 15
Common uses of /
are for sum with +
, product with ×
, all with ∧
, and any with ∨
.
\
(scan) is a similar monadic operator. It reduces each prefix of the last axis. For a vector this means that f\a b c d...
is (f/a) (f/a b) (f/a b c) (f/a b c d) ...
A common use is for cumulative sum:
+\2 3 5 7 11
+\3 4⍴⍳12
Similarly \
also has a twin ⍀
who behaves as you might expect. Scan on first axis.
+⍀3 4⍴⍳12