4 ms·
You'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
by thinkpad20 11y ago
You'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.