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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Haskell,
caseand pattern matching are inextricably linked; you can’t have one without the other.if p then e1 else e2is 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
casestatements 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
ifis equivalent to one case expression).