I am just beginning Haskell, but from all the online tutorials I’ve found I can’t seem to find if there is one accepted way to do a conditional control statement. I have seen if-else, guards, and pattern matching, but they all seem to accomplish the same thing. Is there one generally accepted/faster/more efficient way than the rest?
Share
Guards are (rather complex) syntactic sugar for if-then-else following pattern matching. If-then-else is syntactic sugar for
caseoverBool. So these things are mostly equally efficient.But here’s an observation: it’s often easy to do inefficiently with a Boolean expression what is efficient with a pattern match. A favorite example of beginning Haskell programmers is to write
which costs proportional to the length of
xs, wherecosts constant time.
A more precise way to observe what’s going on is that (absent fancy extensions like view patterns), the worst-case cost of a pattern match is proportional to the number of constructors appearing on the left-hand side—you just can’t write a pattern match that is both expensive and small. By contrast, the size of a Boolean expression tells you nothing about what it costs to evaluate it. In this sense, and in this sense only, pattern matching is cheaper than if-then-else or guards.
A good heuristic for beginners is to use pattern matching wherever you possibly can. As you get more experience, you can refine your approach.