Search code examples
haskellbooleanevaluationstrictor-operator

Non-strict vs. strict OR-operator


This one is fairly simple, but I haven't found a satisfactory answer anywhere else. It's about a strict vs. a non-strict operator, in this case a simple OR.

Have I understood correctly that with a strict operator, you ALWAYS have to look at the second of two Boolean values, like this:

strict_or False True = True strict_or True False = True and so on?

How about the non_strict operator, does this one always only look at the first value, or does it require 2 True values for returning True?

i.e. or True False = True vs. or True False = False?

The way it looks now, there are still some logical mistakes in my code:

or' :: (Bool,Bool) -> Bool
or' (True, True) = True
or' (True, False) = False
or' (False, _) = False


strict_or :: (Bool, Bool) -> Bool
strict_or (True,True) = True
strict_or (False, True) = True
strict_or (False, False) = False
strict_or (True, False) = True

Solution

  • Regardless of whether you have a strict or non-strict or it always gives the same answer given the same boolean values, so

    True  or True  -> True
    False or True  -> True
    True  or False -> True
    False or False -> False
    

    The only case where the strictness matters is that if you have an expression A or B where the B sub-expression might a) take a long time (or even forever!) to calculate or b) potentially throw an exception.

    A strict or will always run the potentially long calculation whereas a non-strict or can "short circuit" if the first parameter is True and hence never evaluate the second parameter at all. This also means that if the second sub-expression throws an exception when it's evaluated you'll get a boolean table like this for strict or:

    True  or <exception> -> <exception>
    False or <exception> -> <exception>
    

    But for non-strict or you'll have

    True  or <exception> -> True
    False or <exception> -> <exception>
    

    Note that all of the above assumes that the non-strict or is non-strict over its second parameter (like it is in Haskell and most other programming languages) but you could also have a non-strict or that is non-strict for its first parameter.