Pattern Matching
Pattern matching is a mechanism for checking a value against a pattern.
Syntax
A match expression has a value, the match
keyword, and at least one case
clause.
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];const result = binarySearch(data, 3);match result { case Some(_) => print("1: found") case None => print("1: not found")}
Match Literal Value
Match expressions have a value.
function myNot(v: boolean): boolean { match v { case true => false case false => true }}
function isSix(num: i32): boolean { match num { case 6 => true case _ => false }}
Match Enumerations
let a = Some(1);match a { case Some(i) => { print("Some") } case None => { print("None") }}
Match Arrays
Match an array with fixed length:
function isOneTwoThree(arr: i32[]): boolean { match arr { case [1,2,3] => true case _ => false }}
Match an array with unlimited length:
function isOneTwoThreeMore(arr: i32[]): boolean { match arr { case [1,2,3, ..._] => true case _ => false }}
Binding variable to pattern:
function printRest(arr: i32[]) { match arr { case [1,2,3, ...rest] => print(rest) case _ => {} }}