乐正

Actions speak louder than words.

Sicp-ex4-12

问题

过程set-variable-value!define-variable!lookup-variable-value可以基于更抽象的遍历环境结构的过程描述。请定义有关的抽象,使之能抓住其中的公共模式,而后基于这些抽象重新定义上述三个过程。

解答

练习4.12 (ex4-12.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
(define (env-loop env base match)
  (let ((frame (first-frame env)))
    (define (scan vars vals)
      (cond ((null? vars)
             base)
            ((eq? var (car vars))
             match)
            (else (scan (cdr vars) (cdr vals)))))
    (scan (frame-variables frame)
          (frame-values frame))))

(define (lookup-variable-value var env)
  (env-loop env
            (env-loop (enclosing-environment env))
            (car vals)))

(define (set-variable-value! var val env)
  (env-loop env
            (env-loop (enclosing-environment env))
            (set-car! vals val)))

(define (define-variable! var val env)
  (env-loop env
            (add-binding-to-frame! var val frame)
            (set-car! vals val)))

draft

« sicp-ex4-11 sicp-ex4-13 »

Comments