Daily Thought - 2024-08-18
< back to listI believe that pattern-matching functions are a powerful primitive that can serve as the foundation for all control flow. Let's see how we can implement common control flow constructs based on them.
In addition to the syntax I proposed yesterday, I'm using
eval
here, which evaluates an anonymous function. Let's start with a simple
if
expression in Rust:
if condition {
handle_then();
} else {
handle_else();
}
In the (still, but not for much longer) fictional pseudo-Caterpillar syntax, this could map to this:
condition
{
|true| handle_then
|false| handle_else
}
eval
Of course, we'll likely have an if
expression in Caterpillar too. But under
the hood, this is what it would translate to. An anonymous function with two
branches, one matching on true
, the other on false
. (Which are also not in
the language yet; right now we just have numbers.)
Next example, match
expression in Rust:
match n {
0 => handle_zero(),
1 => handle_one(),
n => handle_any(n),
}
That would be a straight-forward translation into a pattern-matching function in pseudo-syntax Caterpillar:
n
{
|0| handle_zero
|1| handle_one
|n| n handle_any
}
eval
Or you could write it as a named function:
n handle_number
# Defined somewhere else:
handle_number: {
|0| handle_zero
|1| handle_one
|n| n handle_any
}
And again, Caterpillar could have a dedicated match
expression too, to make
this syntactically more convenient. But under the hood, if would all be
pattern-matching functions.