switch - pannous/warp GitHub Wiki

switch and match

switch and match pick the first case whose key fits the value. The two words are synonyms.

color = red
switch color { green: "woods!"; red: "fire!" }   // fire!

A case is written key: value or key => value, as in Rust. The word case may stand before any case, as in C and Swift, and Kotlin's when x { 1 -> … } is the same match (with a warning, since when means more than this in warp):

x = 1
match x { case 1: "one"; case 2: "two" }    // "one"

Catch-all

other, _, default and else take whatever no other case took:

match 3 { 1 => "one"; other => "many" }   // many

Without a catch-all, a value no case fits is the run-time error "no case for …". A match on an enum or a sealed set of classes must name every case: leaving one out is a compile error, see pattern-matching.

Alternatives

|, or and a comma list several keys for one case:

match 2 { 1 | 2 => "small"; _ => "big" }    // small
match 2 { 1 or 2 => "small"; _ => "big" }   // small
match 2 { 1, 2 => "small"; _ => "big" }     // small

Inside a case key | separates alternatives; elsewhere it stays the logical or. A computed comparison goes in a guard (below).

Ranges

A range as key takes every value in it:

age = 15
match age { 0 to 12 => "child"; 13 to 19 => "teen"; other => "adult" }   // teen

13 to 19 and 13...19 include 19, 13..20 stops before 20, 65.. has no end.

Guards

if after a key adds a condition:

f(n) := match n { 0 => "zero"; n if n < 0 => "negative"; _ => "positive" }
f(-5)   // negative

Types

A type word as key tests the value's type; name: type also names it:

describe(v) := match v { i: int => i + 1; t: text => t + "!" }
describe(3)     // 4
describe("a")   // a!

Class names test instances (Circle => …), and types mix with values: 0 or text => …. The same test outside a match is is: x is (int or text).

Lists, tuples, maps and enum cases with values are matched by their shape: pattern-matching.

Like map indexing

A switch is close to indexing a map of actions, {green: "woods!", red: "fire!"}[color]. The difference: a switch runs only the case it picks, and falls back to its catch-all where the map fails with "key not found".

⚠️ **GitHub.com Fallback** ⚠️