</> APL Run Loading interactive WebAssembly workspace…

🎓 Chapter 6: Dynamic Functions (Dfns) & Control Flow

In modern APL (Dyalog and mAPL), user-defined functions are written using Dfns (Dynamic Functions) enclosed in curly braces {...}.

---

1. Dfn Argument Symbols

Inside a dfn:

  • ⍵ (Omega): Represents the Right Argument.
  • ⍺ (Alpha): Represents the Left Argument (in dyadic calls).

Simple Monadic Dfn:

```apl

Square ← { ⍵ × ⍵ }

Square 9 ⍝ Returns 81

```

⍝ Define a monadic squaring dfn
Square ← { ⍵ × ⍵ }
Square 9

---

2. Dyadic Dfns (Two Arguments)

A dyadic dfn uses both ⍺ (left) and ⍵ (right):

```apl

Hypot ← { ( (⍺*2) + (⍵*2) ) * 0.5 }

3 Hypot 4 ⍝ Returns 5

```

⍝ Hypotenuse function √(a² + b²)
Hypot ← { ((⍺*2) + (⍵*2)) * 0.5 }
3 Hypot 4

---

3. Guards & Early Return (condition : expression)

A Guard (:) provides conditional control flow inside a dfn.

If condition evaluates to 1 (True), the dfn returns expression immediately and terminates execution.

⍝ Safe division dfn: returns 0 if denominator is 0
SafeDiv ← { ⍵ = 0 : 0 ⋄ ⍺ ÷ ⍵ }
10 SafeDiv 2 ⋄ 10 SafeDiv 0

---

4. Self-Recursion (∇)

Inside a dfn, the symbol ∇ (Del) refers to the dfn itself, allowing clean recursive function definitions!

⍝ Recursive Factorial dfn using self-reference (∇)
Fact ← { ⍵ ≤ 1 : 1 ⋄ ⍵ × ∇ (⍵ - 1) }
Fact 6

← Chapter 5: Outer Products (∘.) & Table Math Chapter 7: Each (¨) & The Rank Operator (⍤) →