3 ms·
Is pattern matching really that different from switch statements, which are really just fancy of statements? Mostly, yes. Pattern matching also provides destru
by danieldk 14y ago
Is pattern matching really that different from switch statements, which are really just fancy of statements?
Mostly, yes. Pattern matching also provides destructuring, allowing you to bind constructor arguments and pattern match against such arguments as well. For instance:
fun (Just (x:_)) = ...
But some of the downsides are comparable to switch statements, e.g. if you modify:
data MyType = Foo | Bar
to
data MyType = Foo | Bar | Baz
You will have to (potentially) update all functions or case expressions to account for Baz. One could use parametric polymorphism, comparably to the linked article, to make more extensible code. In such a case, one would define a type class such as:
class (Show a) => Printer p where
printIt :: p -> a -> IO ()
And one could make particular printers of this typeclass. You could even throw in existential quantification so that a function does not specialize to a particular Printer.