by kinghajj · 10y ago · 0 comments
data Thing
= Foo String
| Bar Int Double
| Baz String String
case thing of
Foo s -> putStrLn s
Bar i f -> -- ...
Baz s1 s2 -> -- ...
If you later add another variant to Thing, the compiler will check that all pattern matches against it account for the new case. (Wildcard matches alleviate the need always to handle every case.) An if-elseif chain, however, would still compile after adding the new variant, so you must track down the usages manually.And indeed, when you look at a language like Nim and Swift, that's exactly what happened. Rust, too, although Rust is arguably a functional language.
foo(bar) -> baz;
foo(X) -> bang.
The X is an explicit variable that will match anything not already matched in previous patterns. It can also be used. (NB: Erlang pattern matching is the same or essentially the same for this discussion at each possible level, whether in a function declaration as above or a case statement or when receiving messages.)Here, we don't care about the thing we've named with an underscore:
tail([_|Tail]) -> Tail.
In Erlang, `[1|[2,3]]` is equivalent to the list `[1,2,3]`. So `[H|T]` as a pattern would have `H = 1` and `T = [2,3]`. Since we don't care about the head of the list, we name it with _. Optionally, in Erlang, you can give it a fuller name: tail([_Head|Tail]) -> Tail.
The compiler knows that _Head is supposed to be unused and won't complain (warning about unused variables). tail([Head|Tail]) -> Tail.
Would give a warning. obj match {
case Foo(x) => ...
case Bar(y, z) => ...
// no Baz here
}That's not really required for pattern matching. Certainly makes it more useful, and most implementations have it, however.