sicp.io
4.1.10 · Separate analysis from execution

Analyze once, then run the plan many times.

An analyzer can turn expression data into a procedure that accepts an environment and performs only the remaining value lookups and operations.

Guiding question

Which work can be done before the expression receives an environment?

  • Turn each expression node into an execution procedure
  • Capture analyzed operand plans in a closure
  • Reuse one plan with multiple environments

analyze walks the expression tree before any variable values are known. It selects each operator and recursively builds a procedure for every operand.

The resulting plan accepts an environment. Running it only looks up variables, runs the stored operand plans, and applies the already selected operator. One analyzed plan can therefore serve many environments.

SICP code837 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 analyzes one expression and returns (11 25) from two environments.

    Trace focus

    Separate the initial analyze applications from the later plan applications. The expression structure is traversed once before either environment is supplied.

    Try it yourself

    Change the program and compare the result.

    Add a third environment where x is 1 and y is 100. Reuse plan without calling analyze again.

    Show hint

    Only add another plan application to the final list.

    Complete this lesson

    0 of 23 lessons complete in this chapter0%