Pattern matching
case x of
1 -> true
2 -> false
else -> fail
case c of
'A' -> true
'B' -> false
else -> fail
case s of
"one" -> 1
"two" -> 2
"3" | "three" -> 3
else -> fail
Can match on numeric, character and string literals.
case maybe_x of
Some x -> x
None -> 0
Named tuple and a symbol.
case maybe_x of
is Some -> true
is None -> false
Some and None are types, so is also works.
type Value =
| t@ i32
| t@ String
case value of
x : i32 -> x
s : String -> i32.parse s
The content of value is written into x or s depending on its type.
case value of
is i32 -> value
is String -> i32.parse value
Pattern determines a type of the value binding in each arm.
case key of
Key/Enter -> ...
Key/C if mods.contains KeyModifiers/Control -> ...
...
The guard condition is checked if the pattern matches.
case (maybe_x, maybe_y) of
Some x, Some y -> x + y
Some x, None -> x
None, Some y -> y
None, None -> 0
Tuple parentheses can be omitted.
case maybe_vector of
Some vector@mut_ref -> vector.x = 0
None -> ()
maybe_vector is modified if it contains a Some value. @ref, @ptr and @mut_ptr are also available.
case button
of MouseButton/Left -> ...
else MouseButton/Right -> ...
else ->
...
Another syntax for case of reduces the number of indents from two to one.
if maybe_x ? Some x then
println x
The expression in condition tests maybe_x against a single pattern.