Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more efficient in Haskell; pattern matching or nested if/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.

like image 326
Nope Avatar asked Jan 09 '09 03:01

Nope


People also ask

Is pattern matching faster than if else?

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.

Does Haskell have pattern matching?

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.

How does pattern matching work in Haskell?

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.


1 Answers

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

like image 143
Norman Ramsey Avatar answered Nov 16 '22 02:11

Norman Ramsey