🎓 Chapter 4: Reductions & Cumulative Scans
In conventional programming, calculating a sum or running total requires allocating an accumulator variable and running a loop.
In APL, you use Operators like Reduction (/) and Scan (\)!
---
1. Reduction (f/)
Reduction (f/ Y) places any primitive function f between all elements of vector Y.
Examples:
- Sum Reduction (
+/):+/ 1 2 3 4→1 + 2 + 3 + 4 = 10 - Product Reduction (
×/):×/ 1 2 3 4→1 × 2 × 3 × 4 = 24 - Max Reduction (
⌈/):⌈/ 3 8 2 9→ Maximum element =9 - Min Reduction (
⌊/):⌊/ 3 8 2 9→ Minimum element =2
⍝ Sum and product of vector 1..5
(+/ 1 2 3 4 5) ⋄ (×/ 1 2 3 4 5)
---
2. Cumulative Scans (f\)
While Reduction collapses an array down to a single number, Scan (f\ Y) keeps intermediate cumulative results after each step!
Examples:
- Cumulative Sum (
+\):+\ 1 2 3 4→1, 1+2, 1+2+3, 1+2+3+4=1 3 6 10. - Running Maximum (
⌈\):⌈\ 3 8 2 9 4→3 8 8 9 9.
⍝ Cumulative sum scan of numbers 1..10
+\ ⍳ 10
---
3. Matrix Reductions (Row vs Column Aggregation)
On 2D matrices:
- Row Reduction (
f/ M): Collapses columns to compute row-wise totals. - Column Reduction (
f⌿ M): Collapses rows to compute column-wise totals.
M ← 3 4 ⍴ ⍳ 12
⍝ Row sums vs Column sums
(+/ M) ⋄ (+⌿ M)← Chapter 3: Array Arithmetic & Boolean Masks Chapter 5: Outer Products (∘.) & Table Math →