Re:Show HN: Switch statement + lambdas = pattern matching in...
by flinkerflitzer on Saturday September 07, 2024 @10:47PM
(#41477853)
That's an interesting observation. Thanks for taking the time to think critically about my implementation. I posted about this on Reddit and someone pointed out something similar.
I'll link that post for reference: https://www.reddit.com/r/ProgrammingLanguages/comments/1fb5y...
The gist (hehe) was that a full lambda expression in a `passes` case could often feel like overkill. This was the possible solution I suggested:
What I could do is similar to what you suggested in another comment and similar to what C# does, where I add a third type of case that implicitly substitutes the control expression into a longer expression. Something like this, tentatively using the keyword `matches`:
int x = rand(0, 11);
when (x + 2) {
matches _ < 5 || _ > 9 -> { /* body */ }
}
Here is a structural matching example: orientation(image img -> string) {
when (img) {
matches _.width == _.height -> return "square";
matches _.width > _.height -> return "landscape";
otherwise -> return "portrait";
}
}
DeltaScript pattern matching seems to be missing two major features; perhaps intentional because the implementation is more difficult:
1. Binding - useful to be able to assign variables to sub-parts of the control value.
2. Structural matching - matching based on the shape of the control value.
I suppose both binding and structural matching can be accomplished with more verbose `passes` tests. (Also some redundant code to get the bindings; perhaps the `passes` test could return optional bindings.)
[1]: https://github.com/tc39/proposal-pattern-matching