Pattern matching
Pattern matching is the primary form of branching in kex. It works in
function clauses, match expressions, and destructuring
bindings.
match expressions
fizzbuzz.kex
let fizzBuzz(n: Int) -> String do
match (n.modulo(3), n.modulo(5)) do
(0, 0) -> "FizzBuzz"
(0, _) -> "Fizz"
(_, 0) -> "Buzz"
(_, _) -> "${n}"
end
end Multi-clause functions
Define the same function several times against different patterns. Clauses are tried top to bottom.
clauses.kex
let factorial(0) = 1
let factorial(n: Int) = n * factorial(n - 1)
let head([h, *_]) = h
let head([]) = None Destructuring
destructuring.kex
let (q, r) = divmod(10, 3)
match result do
Ok(n) -> "got ${n}"
Error(e) -> "failed: ${e}"
end
match opt do
Just(user) -> user.email
None -> "no email"
end if let
iflet.kex
if let Just(largest) = shapes.max { |s| s.area }
IO.printLine("largest area: ${largest}")
end Guards
A trailing if narrows a clause. The clause only fires if the
guard holds.
guards.kex
match n do
x if x < 0 -> "negative"
0 -> "zero"
_ -> "positive"
end