Exercise 4.22. Extend the evaluator in this section to support the special form let. (See exercise 4.6.)
为 analyze 添加 let? 语句:
(define (analyze exp)
(cond ((self-evaluating? exp)
(analyze-self-evaluating exp))
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((assignment? exp) (analyze-assignment exp))
((definition? exp) (analyze-definition exp))
((if? exp) (analyze-if exp))
((lambda? exp) (analyze-lambda exp))
((begin? exp) (analyze-sequence (begin-actions exp)))
((cond? exp) (analyze (cond->if exp)))
((let? exp) (analyze-let exp))
((application? exp) (analyze-application exp))
(else
(error "Unknown expression type -- ANALYZE" exp))))
在具体分析的时候,我们基本可以完全照搬 练习 4.6 的 let 的转换语句把 let 转化为 lambda 的表达式。我们在这里,最终也只是要调用 analyze 去分析这个 lambda 的表达式而已。
(define (let? exp)
(tagged-list? exp 'let))
(define (let-bindings exp)
(cadr exp))
(define (let-body exp)
(cddr exp))
(define (let-vars bindings)
(map (lambda (x) (car x)) bindings))
(define (let-vals bindings)
(map (lambda (x) (cadr x)) bindings))
(define (let->combination exp)
(cons (make-lambda (let-vars (let-bindings exp))
(let-body exp))
(let-vals (let-bindings exp))))
(define (analyze-let exp)
(dp "analyze-let: " exp)
(analyze (let->combination exp)))