Search code examples
haskellbooleancombinators

Short circuiting (&&) in Haskell


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?


Solution

  • Should be short circuited just like other languages. It's defined like this in the Prelude:

    (&&)                    :: Bool -> Bool -> Bool
    True  && x              =  x
    False && _              =  False
    

    So if the first parameter is False the 2nd never needs to be evaluated.