3 ms·
Pattern matching is a lot more expressive that switch and if statements, as it combines testing with elimination. For instance, let's say we want to write a new
by ulrikrasmussen 14y ago
Pattern matching is a lot more expressive that switch and if statements, as it combines testing with elimination. For instance, let's say we want to write a new tail function, which returns the tail of a list but returns [] when the list is empty (pseudo-Haskell):
tail2 xs = case xs of { Nil => []; Cons(x,xs) => xs }
tail2' xs = if xs == Nil then [] else tail xs
In the second case, tail2', the compiler won't stop us if we switch the two branches. In the first case, tail2, we only get access to the tail of the list if the list is actually non-empty.
In essence, the difference is that if statements throws away any static information about the test result, whereas pattern matching constructs lets that information flow to each branch through variable binding.