読者です 読者をやめる 読者になる 読者になる

SICPゼミ第45回

練習問題4.16

(define (lookup-variable-value var env)
  (define (env-loop env)
    (define (scan vars vals)
      (cond (( null? vars)
             (env-loop (enclosing-environment env )))
            ((eq? var (car vars ))
             (if (eq? (car vals) '*unassigned*)
                 (error "Unassigned Variable")
                 (car vals)))
            (else (scan (cdr vars) (cdr vals )))))
    (if (eq? env the-empty-environment)
        (error "Unbound variable" var)
        (let (( frame (first-frame env )))
          (scan (frame-variables frame)
                (frame-values frame )))))
  (env-loop env))

b.

(define (scan-out-defines procedure-body)
  (if (null? procedure-body)
      null
      (let ((exp (car procedure-body)))
        (if (definition? exp)
            (let ((var (definition-variable exp)))
              ((make-lambda var
                            (begin (set! var (definition-value exp))
                                   (scan-out-defines (cdr procedure-body))))
               '*unassigned*))
            (cons exp (scan-out-defines (cdr procedure-body)))))))

c. どっちでも問題はないが,make-procedureのほうが効率がいい.make-procedureに入れると,evalの一回だけscan-outするが,procedure-bodyに入れるとapplyするたびにscan-outすることになる.

練習問題4.17

f:id:sicp-zemi:20170426162851j:plain f:id:sicp-zemi:20170426162905j:plain