Sic Exercise 4.12
In this exercise, we use the original representation of the framework, that is, to represent the framework as the sequence of the table, rather than the method in exercise 4.11. To separate the environment traversal from the Framework traversal, I have added two processes:
(Define (scan var frame) "searches for var in the frame. If the value is found, the corresponding vals is returned. If the value is not found, # f is returned. "(Define (iter vars vals) (cond (null? Vars) # f) (eq? Var (car vars) vals (else (iter (cdr vars) (cdr vals) (iter (frame-variables frame) (frame-values frame ))) (define (env-loop var env) "searches for var in all frameworks. If the corresponding vals is found, an error is returned. "(If (eq? Env the-empty-environment) (error "Unbound variable" var) (let (vals (scan var (first-frame env )))) (if vals (env-loop var (enclosing-environment env ))))))
Now our environment is much simpler:
(define (lookup-variable-value var env) (car (env-loop var env)))(define (set-variable-value! var val env) (set-car! (env-loop var env) val))(define (define-variable! var val env) (let ((frame (first-frame env))) (let ((vals (scan var frame))) (if vals (set-car! vals val) (add-binding-to-frame! var val frame)))))
Below, I will give a simple test:
(define vars '(a b c d))(define vals (list 1 2 3 4))(define a (make-frame vars vals))(define env (cons a '()))(lookup-variable-value 'a env)(set-variable-value! 'a 100 env)(lookup-variable-value 'a env)(define-variable! 'e 5 env)(lookup-variable-value 'e env)
The running result is as follows:
11005