I'm just curious about the efficiency of pattern matching in Haskell. What is a simple case of where pattern matching would be better than nested if
/case
statements and then the converse?
Thanks for your help.
Python 3.10 match statements are faster at pattern matching sequences than equivalent if-statements. MUCH faster. The second functions runs 86% faster than the first.
We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.
Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns. When defining functions, you can define separate function bodies for different patterns.
In Haskell, case
and pattern matching are inextricably linked; you can't have one without the other. if p then e1 else e2
is syntactic sugar for case p of { True -> e1; False -> e2 }
. For these reasons, I think it is impossible to produce the examples you ask for; in Core Haskell, everything is equivalent to case
.
In languages in the ML family, the optimizer can often do very impressive things with complex pattern matches. This is more difficult for Haskell compilers; because of lazy evaluation, the pattern-match compiler is not allowed to reorder certain tests. In other words, if you nest case
statements in different ways, you may get different performance, but in Haskell you also get different semantics. So generally the compiler doesn't mess with it.
As far as which way to write your own code, it's safe to assume that the code with the fewest case expressions is the best (keeping in mind that one if
is equivalent to one case expression).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With