SICP练习3.20:序对过程实现下环境模型评估推演(无法绘图)
SICP Exercise 3.20: Textual Walkthrough of the Environment Model for Procedural Pairs
Since you mentioned eye discomfort prevents drawing a formal environment diagram, let's walk through the evaluation step-by-step using the procedural pair implementation from SICP, and map out how the environment structure evolves.
First, here's the core procedural definition of pairs we'll use (all bound in the global environment):
(define (cons x y) (define (dispatch m) (cond ((eq? m 'car) x) ((eq? m 'cdr) y) (else (error "Undefined operation -- CONS" m)))) dispatch) (define (car z) (z 'car)) (define (cdr z) (z 'cdr))
Let's use this example expression sequence to trace the environment model:
(define p (cons 1 2)) (car p) (cdr p)
Step 1: Evaluating (define p (cons 1 2))
When we call (cons 1 2):
- A new local environment e1 is created, whose enclosing environment points to the global environment.
- In e1, the parameters
xis bound to1, andyis bound to2. - Next, we define the
dispatchprocedure insidecons: this creates another local environment e2, whose enclosing environment is e1. Thedispatchprocedure object stores a pointer to e2. - The
consprocedure returns thedispatchprocedure object. - Finally, the global environment binds the variable
pto thisdispatchprocedure.
Step 2: Evaluating (car p)
The car procedure is defined as (lambda (z) (z 'car)), so evaluating (car p) does the following:
- We call
carwith argumentp(which is the dispatch procedure from Step 1). This creates a new environment e3 enclosing the global environment, withzbound to the dispatch procedure. - The body of
caris(z 'car)— this means we invoke the dispatch procedure with the argument'car. - Invoking
dispatchcreates a new environment e4, whose enclosing environment is e2 (since dispatch's procedure object points to e2). In e4, the parametermis bound to'car. - The
condclause checks(eq? m 'car)which is true, so we look up the value ofx. Following the environment chain: e4 → e2 → e1, we findxis bound to1. - The result of
(car p)is1.
Step 3: Evaluating (cdr p)
This follows almost the same logic as (car p):
(cdr p)calls thecdrprocedure, which invokes(dispatch 'cdr).- A new environment e5 is created (enclosed by e2), with
mbound to'cdr. - The
condclause returnsy, which we find in e1 bound to2. - The result of
(cdr p)is2.
Environment Chain Summary
- Global Environment: Binds
cons,car,cdr, and eventuallyp(to the dispatch procedure). - e1: Created when
consis called; bindsx=1,y=2; encloses global environment. - e2: Created when
dispatchis defined insidecons; encloses e1; referenced by the dispatch procedure object. - e4: Created when
dispatchis called forcar; bindsm='car; encloses e2. - e5: Created when
dispatchis called forcdr; bindsm='cdr; encloses e2.
内容的提问来源于stack exchange,提问作者lightning_missile
相关产品推荐
相关产品推荐

