Matching Structured Data
Note: Pattern Matching support is currently only partway through it's planned feature support (and has some open bugs to
be addressed). More to come!
Pattern Matching is much more than just a classic C-style switch statement. In particular, it can be used to match arbitrarily structured data.
Fig 1:
var employee = {name = "Bob", title = "Intern"};
var permission: boolean;
match (employee) {
case {name = "Sarah", title = "Manager"} -> permission = true;
case {name = "Joe", title = "Manager"} -> permission = true;
case _ -> permission = false;
}
print("Permission granted for {employee.name}?: {permission}");
Output:
[0.002s][warning][perf,memops] Cannot use file /tmp/hsperfdata_runner/6 because it is locked by another process (errno = 11)
Permission granted for Bob?: false
Matching Arbitrarily Nested Structured Types
Claro supports pattern matching over arbitrary (i.e. tuple<...>
and struct{...}
) structured types as their
structures are fully known at compile time.
Fig 2:
var player = {name = "Jason", currLoc = (1, 2)};
match (player) {
case {name = "Sarah", currLoc = (3, 4)} -> print("Sarah wins!");
case {name = "Jason", currLoc = (1, 2)} -> print("Jason wins!");
case _ -> print("Keep playing...");
}
Output:
Jason wins!