Evaluation follows expressions while lookup follows frame links.
Run a lexical lesson evaluator and frame operations so variable lookup, procedure creation, application, definition, and assignment appear in one model.
Guiding question
Which environment is used when an expression creates a procedure, and which environment is used when that procedure is later applied?
Represent an environment as an ordered list of frames
Search the nearest frame first during variable lookup
Capture the creation environment inside a compound procedure
Extend that captured environment with a fresh parameter frame on application
Distinguish definition in the first frame from assignment to an existing binding
model-eval handles the listed forms: self-evaluating values, variables, quote, lambda, and application. Evaluating lambda creates compound-procedure data containing parameters, body, and the current environment. Applying that value evaluates the body in a new parameter frame linked to the captured environment, so the inner y call can still find the outer x.
The second program makes frame mutation explicit. Lookup finds local x before global x. set-variable-value! changes the already existing local record, while define-variable! adds y to the first frame. Neither operation changes global x. This explanatory evaluator models the listed forms directly.
The lesson evaluator returns (7 13). The frame mutation program returns (3 4 7 10).
Trace focus
In the evaluator, separate lambda evaluation from procedure application and follow the parent environment captured by each compound value. In the frame program, find the nearest assoc hit, the set-cdr! that changes local x, and the set-car! that adds y to only the first frame.
Try it yourself
Change the program and compare the result.
Add if to model-eval, then evaluate a closure whose body chooses between a local parameter and a captured outer value. Also define a global y and confirm that a local definition shadows rather than mutates it.
Show hint
Evaluate only the selected if branch. A definition always targets the first frame of the supplied environment.