Pattern Matching
Wyn is a compiled programming language with pattern matching built into the language. Match on integers, strings, enum variants, Result types, and Option types. Guards, wildcards, and destructuring are all supported. Match expressions return values.
Basic Match
wyn
fn describe(n: int) -> string {
return match n {
0 => "zero"
1 => "one"
_ => "other"
}
}Guards
wyn
fn classify(n: int) -> string {
return match n {
0 => "zero"
_ if n < 0 => "negative"
_ if n > 100 => "big"
_ => "normal"
}
}String Matching
wyn
fn parse_cmd(cmd: string) -> string {
return match cmd {
"quit" => "exiting"
"help" => "showing help"
_ => "unknown: ${cmd}"
}
}Enum Destructuring
Match on enum variants and extract data:
wyn
enum Shape {
Circle(int),
Rect(int, int)
}
fn area(s: Shape) -> int {
return match s {
Circle(r) => r * r * 3
Rect(w, h) => w * h
}
}Result / Option Patterns
wyn
fn safe_div(a: int, b: int) -> Result<int, string> {
if b == 0 { return Err("division by zero") }
return Ok(a / b)
}
match safe_div(10, 3) {
Ok(v) => println("result: ${v}")
Err(e) => println("error: ${e}")
}wyn
fn find(arr: [int], target: int) -> Option<int> {
for i in 0..arr.len() {
if arr[i] == target { return Some(i) }
}
return None
}
match find([10, 20, 30], 20) {
Some(idx) => println("found at ${idx}")
None => println("not found")
}Match as Expression
Match can be used as an expression that returns a value:
wyn
fn eval(op: string, a: int, b: int) -> Result<int, string> {
return match op {
"+" => Ok(a + b)
"-" => Ok(a - b)
"*" => Ok(a * b)
_ => Err("unknown op")
}
}See Also
- Enums — define variants to match on
- Control Flow —
if/elsefor simple conditions - Error Handling — match on Result/Option