</> APL Run Loading interactive WebAssembly workspace…

🎓 Chapter 3: Scalar Math & Relational Logic

In conventional languages, performing math on list items requires iterating with a for loop. In APL, all primitive functions automatically extend across arrays of any shape!

---

1. Scalar Extension

When a binary operation combines a single scalar on one side with a vector or matrix on the other side, APL automatically applies the scalar operation to every single element of the array.

⍝ Multiply scalar 10 by vector 1..5
10 × ⍳ 5

---

2. Relational Functions (< ≤ = ≥ > ≠)

APL relational functions evaluate element-wise and return a boolean array containing 1 for True and 0 for False.

| Function | Name | Example | Result |

| :--- | :--- | :--- | :--- |

| < | Less Than | 3 < 5 | 1 |

| ≤ | Less Than or Equal | 5 ≤ 5 | 1 |

| = | Equal To | 4 = 7 | 0 |

| ≥ | Greater Than or Equal | 9 ≥ 2 | 1 |

| > | Greater Than | 2 > 8 | 0 |

| ≠ | Not Equal To | 5 ≠ 5 | 0 |

Let's test creating a boolean mask on a vector:

⍝ Create a boolean mask of elements > 5
Numbers ← 3 8 2 9 5 7 1
Mask ← Numbers > 5
Mask

---

3. Array Masking (Filtering without if statements!)

Because 1 represents True and 0 represents False, multiplying a numeric array by a boolean mask keeps values where the mask is 1 and zeroes out values where the mask is 0!

This is known as Branchless Array Filtering.

⍝ Zero out numbers that are not > 5
Numbers × (Numbers > 5)

---

4. Logical Functions (∧ ∨ ~ ⍲ ⍱)

APL supports full boolean logic:

  • And (∧): 1 ∧ 1 = 1, 1 ∧ 0 = 0
  • Or (∨): 1 ∨ 0 = 1, 0 ∨ 0 = 0
  • Not (~): ~ 1 = 0, ~ 0 = 1
⍝ Find numbers that are BOTH > 3 AND < 8
Numbers × (Numbers > 3) ∧ (Numbers < 8)

← Chapter 2: Vectors, Matrices & Reshape (⍴, ⍳) Chapter 4: Reductions (/) & Prefix Scans (\) →