UP | HOME

lazy evaluation

In lazy evaluation, expressions are only computed when they are needed. In contrast, in strict evaluation, all parts of an expression are evaluated before the whole is given a value.

For example, consider this piece of haskell code:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

If lazy evaluation were not used, this would cause an infinite loop. However, the values of the array are only computed as needed. That is, when fibs !! 2 is needed, zipWith computes the sum of fibs !! 0 and fibs !! 1.

Another easier example can be seen in the pseudocode below:

def get_num():
    while True:
        continue
    return 0

a = get_num() //loops forever

c = 0
if False:
   c = a
else:
   c = 0

The infinite loop will never run, because the program will never enter the branch that requires it to run.