-
-
Notifications
You must be signed in to change notification settings - Fork 4
pattern matching
Pattern matching is different to matching by type name in that it matches against data schemes.
Pattern matching goes significantly beyond checking a values type. It adds the ability to specify exactly 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.reverseInPlace(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"
}
Scala example:
myList match { case Nil => 0 case first :: Nil => first * 3 case first :: second :: Nil => first - second case first :: second :: rest => first * second + sum(rest) }