Skip to content

07 · Pattern Matching

Transform a value before matching

A (parse_date -> .Ok(date)) pattern applies the unary transformer to the input, then matches its result. Each attempted view pattern calls the transformer once; successful bindings reuse that result. A failed result continues to the next arm. The transformer must have concrete types and cannot consume or produce linear resources. Use it directly in a pattern; view transformers inside alias bodies are currently rejected.

On this page

A (parse_date -> .Ok(date)) pattern applies the unary transformer to the input, then matches its result. Each attempted view pattern calls the transformer once; successful bindings reuse that result. A failed result continues to the next arm. The transformer must have concrete types and cannot consume or produce linear resources. Use it directly in a pattern; view transformers inside alias bodies are currently rejected.

Complete example

Transform a value before matching.

16-view-patterns.zolo
Playground
// Convert incoming fields at the pattern boundary, then match the typed result.

enum Quantity { Valid(int), Invalid }

fn read_quantity(raw: str) -> Quantity {
    return match raw {
        "one" => Quantity::Valid(1),
        "two" => Quantity::Valid(2),
        _ => Quantity::Invalid
    }
}

fn describe((read_quantity -> .Valid(quantity)): str) -> str = "{quantity} items"
fn describe(_: str) -> str = "unknown quantity"

var total = 0
for case (read_quantity -> .Valid(quantity)) in ["one", "invalid", "two"] {
    total += quantity
}
assert(total == 3)
assert(describe("two") == "2 items")
assert(describe("invalid") == "unknown quantity")
print("Accepted {total} items")

Reference

Reference · Source program

zolo run examples/features/40-syntax-fourth/16-view-patterns.zolo --no-cache

Global index

Find your way through Zolo

Try an idea

Start here

9 results

9 results

enespt-br