(no title)
thinkpad20 | 6 years ago
switch (mylist) {
| [“”, _, “”] => x
| _ => y
}
Moreover, pattern matching usually involves pulling information out of the object at the same time. In the above example, maybe you want to do something with the middle element: switch (mylist) {
| [“”, middle, “”] => middle ++ “!”
| [“foo”, x] => String.reverse(x)
| _ => “never mind”
}
All of this would be possible to do with a series of if conditions, but significantly harder to read and implement correctly.The power of pattern matching grows clearer as more complex data and rules are introduced. For example, it works just as well with nested lists:
switch (mylist) {
| [outer, [middle, [inner]]] => outer ++ middle ++ inner ++ “!”
| _ => “never mind”
}
While having a type system is helpful in all of the ways a type system is generally helpful, there’s nothing about this code which wouldn’t also be handy in a dynamic language like JavaScript. For further evidence of this see Erlang and Elixir, dynamic languages which make heavy use of pattern matching.(Code typed on my iPhone so forgive the dopey examples)
ufo|6 years ago
dllthomas|6 years ago
I agree that matching on multiple levels in one statement isn't common, if that's what you were talking about. But performing bindings in a match is very common, and not something that's part of a switch statement (except in those languages where a switch statement is doing pattern matching more generally anyway).