Pattern Matching
Match expressions, pattern forms, constructor matching, guards, and match errors.
1. Variant declarations
type introduces tagged unions / ADTs.
type Shape:
Circle(r)
Rect(w, h)
Point
Each constructor is a value. Circle, Rect, and Point are matched in match.
2. match expressions
fn area(s):
match s:
Circle(r) => 3.14159 * r * r
Rect(w, h) => w * h
Point => 0
print(area(Circle(2.0)))
print(area(Rect(3, 4)))
print(area(Point))
Output:
12.56636
12
0
3. Pattern kinds
From the grammar and tutorial examples:
- Literal pattern:
0,"x",true - Wildcard:
_ - Binding pattern: lowercase name
- Constructor pattern:
Circle(r),Rect(w, h)
4. Guards and block-bodied arms
type Expr:
Num(n)
Add(a, b)
fn eval(e):
match e:
Num(n) => n
Add(a, b) =>
x = eval(a)
y = eval(b)
x + y
Guards run after constructor matching.
fn label(x):
match x:
0 => "zero"
x if x > 0 => "positive"
_ => "negative"
5. Match order and no-match behavior
match checks arms in source order. The first arm that matches wins.
fn describe(x):
match x:
n => "bound " + str(n)
1 => "one"
_ => "other"
Because n matches anything, later specific arms do not run. The example order is
important.
If no arm matches, Stage-0 reports a runtime error such as no match arm matched value <...>.
6. Option and Result as patterns
match Some(42):
Some(v) => v
None => 0
match Err("bad"):
Ok(v) => v
Err(e) => e
This pattern style is the basis of error recovery in examples across .sources/vela/examples.