Exercise 4.23: Alyssa P. Hacker doesn’t
understand why analyze-sequence needs to be so complicated. All the
other analysis procedures are straightforward transformations of the
corresponding evaluation procedures (or eval clauses) in
4.1.1. She expected analyze-sequence to look like this:
(define (analyze-sequence exps)
(define (execute-sequence procs env)
(cond ((null? (cdr procs))
((car procs) env))
(else ((car procs) env)
(execute-sequence
(cdr procs) env))))
(let ((procs (map analyze exps)))
(if (null? procs)
(error "Empty sequence:
ANALYZE"))
(lambda (env)
(execute-sequence procs env))))
Eva Lu Ator explains to Alyssa that the version in the text does more of the
work of evaluating a sequence at analysis time. Alyssa’s sequence-execution
procedure, rather than having the calls to the individual execution procedures
built in, loops through the procedures in order to call them: In effect,
although the individual expressions in the sequence have been analyzed, the
sequence itself has not been.
Compare the two versions of analyze-sequence. For example, consider the
common case (typical of procedure bodies) where the sequence has just one
expression. What work will the execution procedure produced by Alyssa’s
program do? What about the execution procedure produced by the program in the
text above? How do the two versions compare for a sequence with two
expressions?
练习 4.23:Alyssa P. Hacker 不明白为什么 analyze-sequence 需要写得如此复杂。所有其他分析过程都是对 4.1.1 节中相应求值过程(或 eval 子句)的直接变换。她预期 analyze-sequence 应该长成这样:
(define (analyze-sequence exps)
(define (execute-sequence procs env)
(cond ((null? (cdr procs))
((car procs) env))
(else ((car procs) env)
(execute-sequence
(cdr procs) env))))
(let ((procs (map analyze exps)))
(if (null? procs)
(error "Empty sequence:
ANALYZE"))
(lambda (env)
(execute-sequence procs env))))
Eva Lu Ator 向 Alyssa 解释说,课文中的版本在分析阶段完成了更多对序列求值的工作。Alyssa 的序列执行过程没有将各个执行过程的调用内联构建进来,而是依次循环遍历这些过程并逐一调用:实际上,虽然序列中的各个表达式已经被分析过了,序列本身却并没有被分析。
请比较 analyze-sequence 的两个版本。例如,考虑最常见的情形(典型的过程体):序列中只有一个表达式。Alyssa 的程序所产生的执行过程会做哪些工作?课文中的程序所产生的执行过程又会做哪些工作?对于含两个表达式的序列,两个版本相比如何?
(define (analyze-sequence exps)
(define (execute-sequence procs env)
(cond ((null? (cdr procs))
((car procs) env))
(else ((car procs) env)
(execute-sequence
(cdr procs) env))))
(let ((procs (map analyze exps)))
(if (null? procs)
(error "Empty sequence:
ANALYZE"))
(lambda (env)
(execute-sequence procs env))))