Short circuiting (&&) in Haskell

Viewed 4466

A quick question that has been bugging me lately. Does Haskell perform all the equivalence test in a function that returns a boolean, even if one returns a false value?

For example

f a b = ((a+b) == 2) && ((a*b) == 2)

If the first test returns false, will it perform the second test after the &&? Or is Haskell lazy enough to not do it and move on?

4 Answers

A simple test to "prove" that Haskell DO have short circuit, as Caleb said.

If you try to run summation on an infinite list, you will get stack overflow:

Prelude> foldr (+) 0 $ repeat 0
*** Exception: stack overflow

But if you run e.g. (||) (logical OR) on in infinite list, you will get a result, soon, because of short circuiting:

Prelude> foldr (||) False $ repeat True
True
Related