Which is more effective at Haskell; Matching models or nested case / case statements?


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.

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).