🎓 Chapter 1: Foundations of APL & Array Thinking
Welcome to APL (A Programming Language)! APL is a unique, mathematical array-oriented programming language created by Kenneth E. Iverson.
Unlike traditional programming languages (like C, Python, or Java) that rely on explicit for or while loops to process individual numbers, APL operates directly on entire arrays of numbers at once using single-character mathematical symbols called primitives.
---
1. The Golden Rule of APL: Right-to-Left Evaluation
In standard algebra, operators have precedence (multiplication × happens before addition +).
In APL, there is NO operator precedence! Every function has equal priority, and expressions evaluate strictly Right-to-Left (unless overridden by parentheses ()).
Example Breakdown:
Consider the expression 3 × 2 + 5:
- First (Rightmost): Evaluate
2 + 5, which equals7. - Next (Leftmost): Evaluate
3 × 7, which equals21.
Result: 21! (If evaluated left-to-right, 3 × 2 = 6, then 6 + 5 = 11 — which is NOT how APL works!).
⍝ APL evaluates strictly Right-to-Left!
3 × 2 + 5
To force 3 × 2 to happen first, you must use explicit parentheses ():
⍝ Using parentheses to control evaluation order
(3 × 2) + 5
---
2. High Minus (¯) vs Subtraction (-)
In APL, there is a clear distinction between:
- Negative Number Literals (
¯): Written as a high minus symbol¯5(e.g. `2 `or- ``). This is part of the number itself. - Subtraction Function (
-): Written as a standard hyphen-. EvaluatesA - B(dyadic) or negates a value- B(monadic).
Let's test negative numbers in APL:
⍝ Subtracting a negative number: 10 - (-5)
10 - ¯5
---
3. Monadic Functions (Functions with 1 Argument)
In APL, functions can be Monadic (taking 1 argument on their right: f Y) or Dyadic (taking 2 arguments: X f Y).
Here are fundamental Monadic mathematical primitives:
| Glyph | Name | Monadic Meaning | Example | Result |
| :--- | :--- | :--- | :--- | :--- |
| | | Magnitude / Absolute Value | Computes absolute value of Y | | ¯15 | 15 |
| ⌈ | Ceiling | Rounds Y up to nearest integer | ⌈ 3.14 | 4 |
| ⌊ | Floor | Rounds Y down to nearest integer | ⌊ 3.14 | 3 |
| ÷ | Reciprocal | Computes 1 ÷ Y | ÷ 4 | 0.25 |
| - | Negation | Changes the sign of Y | - 5 | ¯5 |
Let's run each of these in live code cells below!
⍝ Monadic Magnitude / Absolute Value (|)
| ¯15
⍝ Monadic Ceiling (⌈) and Floor (⌊)
⌈ 3.14 ⋄ ⌊ 3.14
⍝ Monadic Reciprocal (÷)
÷ 4
---
✏️ Exercise 1.1: Temperature Conversion
To convert a temperature from Fahrenheit (F) to Celsius (C), we use the formula:
C = (F - 32) × (5 ÷ 9)
Let's calculate the Celsius equivalent of body temperature (98.6°F):
⍝ Convert 98.6°F to Celsius
F ← 98.6
(F - 32) × 5 ÷ 9