sicp.io
3.5.2 · Time as a sequence

A stream reveals only the part you demand.

A stream keeps its first value now and delays the computation that can produce the rest of the sequence.

Guiding question

How can a finite run use a sequence with no final element?

  • Read a stream as a present value and a delayed tail
  • Follow demand through repeated stream-ref calls
  • Distinguish describing an infinite process from executing forever

integers-from can describe an unending sequence because cons-stream does not evaluate its tail immediately. Each tail is a promise for the next pair.

stream-ref forces exactly as many tails as it needs to reach the requested index. Asking for index 9 constructs a finite prefix and returns 10, so this particular run terminates.

SICP code300 of 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Execution trace0 / 0 events
    Programs run in the browser with their result and execution trace.
    Expected result

    The first program returns 10 after forcing nine stream tails.

    Trace focus

    Find the repeated force events. Each computed outcome exposes one more pair, while the unrequested remainder stays delayed.

    Try it yourself

    Change the program and compare the result.

    Change the requested index from 9 to 4. Predict the value and how many stream tails must be forced.

    Show hint

    Index 0 uses the current car without forcing the cdr.

    Complete this lesson

    0 of 21 lessons complete in this chapter0%