Search⌘ K

Lazy Evaluation

Explore lazy evaluation in Haskell and understand how it differs from strict evaluation. Learn how Haskell evaluates function arguments only when needed, enabling termination in cases where strict evaluation would not. This lesson helps you grasp evaluation order effects, pattern matching with non-terminating expressions, and implement lazy function versions for better control.

Evaluation order and termination

Previously, we saw that the order of evaluation does not influence the result of expressions. This changes, however, when non-termination comes into play.

As an example, let’s revisit once more our function both, the reimplementation of the conjunctive boolean && operator:

Haskell
both :: Bool -> Bool -> Bool
both False _ = False
both True b = b
main = do
print (both True True)
print (both False True)

The function both is implemented by pattern matching on the first argument. If the first argument is already False, we know that the result is False and do not need to check the second argument. If the first argument is True, we do need to check the second argument, and its truth value will be the result.

Now, let’s again use our looping function,

loop :: Bool -> Bool
loop x = loop x

and evaluate the expression both False (loop True). A first approach could be to start with evaluating the subexpression loop True:

both False (loop True)
 =
...