Daily Thought - 2024-08-17
< back to listLet's revisit pattern-matching functions, as I've refined how I think about them over the last few days.
First, nomenclature. The developer can define and call functions. A function can be named or anonymous. It has at least one, possibly multiple branches. Each branch defines a list of parameters, in the form of patterns. When the function is called, the first branch whose parameters match the arguments, is selected and evaluated. The other branches are ignored.
Next, syntax. Let's assume that {
and }
are the syntax for defining
functions, and within that, |a b c|
denotes the start of a new branch (in this
case, one with the parameters a
, b
, and c
). While the semantics are
already implemented, Caterpillar still has no syntax. So this is all pseudo-code
that might end up looking completely different.
A simple named function with one branch:
plus_one: { |n| n 1 + }
An anonymous function would just be the part within { ... }
, and could be
defined wherever the parser accepts an expression.
A named function with multiple branches:
handle_input: {
|0| # no input available; do nothing
|1| move_up
|2| move_left
|3| move_down
|4| move_right
|n| "invalid input" panic
}
Here, the call 0 handle_input
would run a different branch than 1 input
, for
example.