Computing Only What Is Needed

Lazy evaluation delays a computation until its value is required and shares the resulting value among later uses of the same binding. You encounter this behaviour in languages such as Haskell, where a program can describe more work than its requested output actually needs. Here, lazy evaluation means call-by-need. We will reason about pure, sequential computations, so evaluating an expression does not change external state.

Demand determines the work

A value is demanded when another computation needs it to proceed. Arithmetic demands numeric operands; a conditional demands enough information to choose a branch. An unused binding need not be evaluated merely because it appears in the program.


Consider this expression, where expensive is a pure function returning a number:


haskell
let x = expensive 6
    unused = expensive 100
in x + x


Producing the final number requires x. Its first demand evaluates expensive 6; the second use reuses that result. Nothing in the requested output demands unused.


For a particular shared numeric binding whose computation completes whenever demanded, the governing counting rule is:


Nevaluations={0,if the binding is never demanded,1,if the binding is demanded one or more times.N_{\text{evaluations}} = \begin{cases} 0, & \text{if the binding is never demanded},\\ 1, & \text{if the binding is demanded one or more times}. \end{cases}


The rule applies to uses of the same shared binding. Two separately written expressions are not automatically one computation just because their text matches. When tracing examples, assume no compiler transformation merges separate expressions unless told otherwise.

Thunks preserve the deferred work

A thunk is a runtime object that holds a deferred expression together with the environment needed to evaluate it. When demand reaches the thunk, the evaluator performs the required computation. After successful evaluation, the thunk can retain the result instead of repeating the expression. This reuse is an instance of memoization.


A deferred expression becomes an active computation on demand and then a stored result after successful evaluation.


Use of a shared numeric binding

What happens

Completed evaluations

No use demands its value

Its expression remains deferred

0

One use demands its value

Its expression is evaluated

1

Several uses demand its value

The first computes; later uses reuse

1



Sharing is associated with a particular runtime binding. If x depends on another shared binding y, computing x may demand y, but later demands for either binding can reuse its own stored result.

Demand can stop partway through a structure

Lazy evaluation can produce only the portion of a structure that its consumer needs. A list consists of cells and element computations; discovering another cell does not necessarily require evaluating that cell's element.


Example: In Haskell, sum (take 4 [1..]) produces 10. The list notation describes an unbounded sequence, but summing the requested prefix requires only the first four numbers. The program does not first construct an infinite completed list.


This distinction matters when counting work. Moving past a list element may require its surrounding cell without requiring the element's numeric value. Conversely, summing a prefix demands each number in that prefix.



The benefit depends on what the consumer requests. Avoiding unused work can save time, while deferred expressions and cached results also occupy memory. Demand only as much structure as the requested result requires, and distinguish that structure from the values stored within it.

What to remember

  • Follow demand backward from the requested output.
  • A shared binding computes its result once and reuses it after successful evaluation.
  • Unused computations can remain deferred.
  • A lazy structure can be consumed partly without evaluating every element.

Example: Decoding a Sensor Report on Demand

A sensor-reporting tool uses pure lazy evaluation with sharing. A thunk holds a deferred computation and retains its result after successful evaluation. In this simplified timing model, decoding frame A returns 28 and costs 6 ms; decoding frame B returns 19 and costs 4 ms; decoding frame C returns 42 and costs 9 ms. Ignore arithmetic, comparisons, allocation, and lookup costs. Assume no compiler transformations.


haskell
let current = decode frameA
    previous = decode frameB
    spare = decode frameC
in if current > 20
   then current + current - previous
   else previous


Treat addition and subtraction as left-associative. After the report is produced, an inspector can request these values again; all later requests retain the same bindings and cached results.


a) Which bindings must be evaluated to choose the branch and produce the report? How many decoding calls occur before the report is available?


Choosing the branch requires the value of current. Decoding frame A gives ________, so the comparison with 20 is true and the selected branch is current + current - previous.


Both occurrences of current reuse its stored value. The subtraction also requires previous, so frame B is decoded. The binding spare is never demanded while producing this report.


The number of demanded bindings is 2. Each is decoded once, so 2 decoding calls occur, for current and previous.


b) What numeric value does the report return?


The selected branch uses the cached value 28 twice and the value 19 once. First compute the addition, then perform the subtraction.


The intermediate addition is ________. Therefore,


report=(28+28)−19=56−19=37.\text{report} = (28+28)-19 = 56-19 = 37.


The report returns 37. Reusing current means reusing its value, not omitting its second contribution to the arithmetic.


c) After the report finishes, the inspector requests previous twice and then spare once. Find the additional decoding time and the total decoding time including the original report.


The original report decoded frames A and B, so its decoding time was


Creport=6 ms+4 ms=10 ms.C_{\text{report}} = 6\ \text{ms}+4\ \text{ms}=10\ \text{ms}.


That original time is ________. Both later requests for previous reuse 19, adding no decoding time. The first request for spare finally demands frame C, adding 9 ms and storing its value 42.


Ccombined=10 ms+9 ms=19 ms.C_{\text{combined}} = 10\ \text{ms}+9\ \text{ms}=19\ \text{ms}.


The inspector adds 9 ms of decoding time, and the combined decoding time is 19 ms. Across the whole interaction, each of the three retained bindings is decoded once.

A pure language uses lazy evaluation with sharing. Evaluate the following expression, where div means integer division. Only the final expression's value is requested.


haskell
let broken = 9 `div` 0
in 23


What happens when the requested value is produced?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A lazy language represents a pair using the constructor Pair. Both integer fields remain delayed until demanded. Consider this binding:


haskell
value = Pair (18 + 7) (6 * 9)


Complete the statements using the full names of the evaluation states, rather than their abbreviations.


After exposing Pair while leaving both field expressions unevaluated, value is in . After evaluating both integer fields completely, value is in .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A telemetry tool evaluates this pure expression using lazy evaluation with sharing. Decoding storedFrame returns 16 and takes exactly 12 ms. Each numeric addition takes exactly 1 ms.


haskell
let base = decode storedFrame
    adjusted = base + 5
in adjusted + adjusted + base


Assume no compiler transformations, and ignore allocation, lookup, and all other overhead. How much time is required to produce the final number? Answer in ms, to the nearest whole millisecond.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice