|
|
|
|
|
by thinkpad20
2401 days ago
|
|
Pattern matching goes significantly beyond checking “foo.type”. It adds the ability to specify exactly (as exact as the language and your data allows) what case you’re dealing with. For example, a list of length three where the first and last elements are empty strings. Having to specify this with a series of if statements often leads to verbose and error-prone code, but it’s trivial in a language like reasonml: 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) |
|