← back to programming

Environment Model

Abelson & Sussman ยท 1996 ยท SICP ยง3.2

The environment model replaces substitution when mutation exists. A closure is a procedure + the environment in which it was defined. Frames chain into scope.

global env square: (* x x) E1 x: 5 Closure points to defining environment; E1 extends it

Rules for evaluation

In the environment model, every expression is evaluated with respect to some environment. The two key rules:

  1. To evaluate a combination, evaluate the subexpressions in the current environment, then apply the procedure to the arguments.
  2. To apply a procedure, create a new frame that binds the parameters to the arguments, extend the procedure's environment with this frame, and evaluate the body in the new environment.
Scheme

Applying simple procedures

When a procedure is applied, the new frame's enclosing environment is the one where the procedure was defined, not where it is called. This is lexical scoping.

Scheme

Frames as repositories of local state

set! modifies a binding in place within its frame. The frame persists as long as the closure references it. This is how local state works: the frame is the state.

Scheme

Internal definitions

Internal defines create bindings in the procedure's frame. They are visible only within that procedure. This gives us block structure without any special mechanism.

Scheme
Scheme

Notation reference

Concept Scheme Python
Frame(define ...) in bodyLocal scope of a function call
Enclosing envWhere lambda was evaluatedClosure's __closure__
Binding(define x 5)x = 5
Mutation(set! x 10)x = 10 / nonlocal x
Block structureInternal defineNested def

Translation notes

Neighbors
Ready for the real thing? Read SICP §3.2.