SICP 中评估者的矛盾假设

Contradictory assumptions on evaluator in SICP

练习 1.6 定义了 new-ifcond:

(define (new-if predicate then-clause else-clause)
  (cond (predicate then-clause)
        (else else-clause)))

这个new-if在递归调用时会陷入无限循环。

示例 sqrt-iter 说明了参数在传递到 user-defined 函数后立即求值的事实。

3.5中引入的(infinite)stream也定义了一个函数:

(define (cons-stream a b)
  (cons a
        (delay b)))

根据教科书,构建它的关键点是delay

但是假设您构建了一个流:

(define (intgers-starting-from n)
  (cons-stream n
               (intgers-starting-from (+ n 1))))

(define integers (intgers-starting-from 1))

使用与 new-if 中相同的求值器,您将无法正常工作,因为 (intgers-starting-from n) 总是会求值 (intgers-starting-from (+ n 1)) 并且显然没有尽头,尽管 delay 已实施。

SICP 假设这样的评估器适用于 cons-stream 但不适用于 new-if 这是否矛盾?

SICP says:

Cons-stream is a special form defined so that

(cons-stream <a> <b>)

is equivalent to

(cons <a> (delay <b>))

It also adds:

Although stream-car and stream-cdr can be defined as procedures, cons-stream must be a special form. If cons-stream were a procedure, then, according to our model of evaluation, evaluating (cons-stream <a> <b>) would automatically cause <b> to be evaluated, which is precisely what we do not want to happen. For the same reason, delay must be a special form, though force can be an ordinary procedure.

根据定义,特殊形式不是过程或函数。所以,你对 cons-stream 的定义是不正确的。

通常以宏的形式实现:

(define-syntax cons-stream
  (syntax-rules ()
    ((cons-stream a b)
     (cons a (delay b)))))

确实,您可以将 new-if 定义为宏,它也可以正常工作:

(define-syntax new-if
  (syntax-rules ()
    ((new-if predicate then-clause else-clause)
     (cond (predicate then-clause)
           (else else-clause)))))