6.6. Pattern matching

The MATCH module implements pattern matching on variants, structs, tuples, arrays, and scalar values. Supports variable capture ($v(name)), wildcards (_), guard expressions (&&), and alternation (||).

match is a statement, not an expression — write the arms so each one assigns or returns, rather than expecting the match itself to produce a value. Arms are tried in source order and the first one that matches wins; a pattern that cannot apply to the subject type is a compile error. static_match drops such arms silently instead of erroring, which is what makes it usable in generic code where only some arms apply per instantiation. multi_match / static_multi_match run every matching arm instead of stopping at the first.

See Pattern Matching for a hands-on tutorial.

All functions and symbols are in “match” module, use require to get access to it.

require daslib/match

Example:

require daslib/match

enum Color {
    red
    green
    blue
}

def describe(c : Color) : string {
    match (c) {
        if (Color.red) { return "red"; }
        if (Color.green) { return "green"; }
        if (_) { return "other"; }
    }
    return "?"
}

[export]
def main() {
    print("{describe(Color.red)}\n")
    print("{describe(Color.green)}\n")
    print("{describe(Color.blue)}\n")
}
// output:
// red
// green
// other

6.6.1. Call macros

static_multi_match

Implements static_multi_match macro.

multi_match

Implements multi_match macro.

match

Implements match macro.

static_match

Implements static_match macro.

6.6.2. Structure macros

match_copy

Implements match_copy annotation. This annotation is used to mark that structure can be matched with different type via match_copy machinery.

match_as_is

Implements match_as_is annotation. This annotation is used to mark that structure can be matched with different type via is and as machinery.