3 ms·
When I think of 'pattern matching' I think of some complex idea like brain-level parsing of text to an AST via matching of syntax patterns. But what OCaml patte
by hacker_9 11y ago
When I think of 'pattern matching' I think of some complex idea like brain-level parsing of text to an AST via matching of syntax patterns. But what OCaml pattern-matching really is is just the equivalent of a C# switch statement, or if/else-if statements.
- mbrock 11y agoYou might think of that but that's not what it means in this context. ML-style pattern matching is a concise way to match nested structures and simultaneously bind variables to arbitrary subelements, which is particularly useful when combined with algebraic data types. Both are classic features of ML and derived languages since the early 70s. They're not buzzwords just because you don't know what they mean.
- thinkpad20 11y agoYou're right that pattern-matching in functional languages resembles a switch statement. In a way it generalizes the concept of a switch statement, in the sense of "doing different things based on the shape of the object at runtime." However, it's quite a bit more powerful. Here's a simple and oft-used example, which is option types. They correspond roughly to nulls so let's compare two blocks of pseudocode: // traditional if myValue == null: print("nothing here!") else: print("value is " ++ myValue) // with pattern-matching switch myValue: case None: print("nothing here!") case Some(thing): print("value is " ++ thing) The two appear similar on the surface, but in the first example, we are relying on the programmer to check that myValue is not null. If he or she fails to check this, we'll likely throw an exception or worse. On the other hand in the second case, we do not need to trust anyone; instead we guarantee that there will be a non-null value added to the string, because it won't be possible to "extract" the inner value from myValue without entering a context in which myValue has a `Some` form. There is a lot more safety this way, since it's guaranteed by the language rather than the programmer. And not only is it more safe, but it's a lot clearer and more expressive as well. Consider a type with more than two variants, or holding multiple internal values rather than just one. The imperative if/then/else solution rapidly becomes verbose, obscure and error-prone, while the pattern matching case is just as straightforward as the above example. It might seem weird on the surface but after a few times using it it's the simplest thing in the world and you'll wish you had it in other languages. In fact, Rust, which isn't (primarily anyway) a functional programming language, makes heavy use of pattern matching.