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.
-
I didn't confirm this, but I think both forms will become a nested case-of expression when translated to core Haskell by the compiler. The best way to find out is asking the compiler itself. In GHC you can turn on the dump of the core intermediate program by using the arguments:
- Before simplifications: -ddump-ds
- After simplifications: -ddump-simpl
-
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 forcase 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 tocase
.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).Jon Harrop : Can you elaborate on the laziness issue? Is it to retain performance characteristics? -
According to the specification, they are semantically equivalent. This, of course, does not necessarily mean that they are implemented identically, but I would personally be surprised if there was a difference in a decent compiler.
0 comments:
Post a Comment