I wouldn't call it a party trick, but I also wouldn't say it's the most common use of case by a long shot. I don't expect that you disagree.
I wouldn't call it a party trick, but I also wouldn't say it's the most common use of case by a long shot. I don't expect that you disagree.
Nevertheless, if that was the only benefit of it, one might argue it’d be more of a party trick. But it’s simply one more facet of a very powerful, simple-to-use technique for expressing how your code reacts to the shape of your data.
I’m curious how much exposure you’ve had to languages which support it — you might find it more useful than you think.
The real benefit of pattern matching is the compiler checking at least that you have valid cases, and ideally that you haven't missed any cases.
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)
I can’t count how many times I’ve seen error messages that look like this, often with no context at all, in JavaScript apps, even widely used ones like npm and webpack. Proper error handling is never easy, but the JS community seems particularly given to avoiding it.
We don't have a counterfactual Twin Earth where those countries did not have slaves, but we know for sure slavery is not necessary for a country to be successful. And if we look at countries that had way more slaves, the advantage of simply having slave labor seems hugely insufficient for a country to be successful.
It is possible that the USA had slaves and was able to economically leverage them far greater than all the other countries that had slaves, but this seems unlikely, and such a scenario would also be the biggest gain for a counterfactual scenario that the USA would have been successful without them, too.
I haven't used it myself but it's pretty cool that it's out there.