SICP 全笔记

Exercise 4.27. Suppose we type in the following definitions to the lazy evaluator:

(define count 0)
(define (id x)
  (set! count (+ count 1))
  x)

Give the missing values in the following sequence of interactions, and explain your answers.38

(define w (id (id 10)))
;;; L-Eval input:
count
;;; L-Eval value:
<response>
;;; L-Eval input:
w
;;; L-Eval value:
<response>
;;; L-Eval input:
count
;;; L-Eval value:
<response>

输入与输出

下面是解释器中的输入与输出:

;;; L-Eval input:
(define count 0)

;;; L-Eval value:
ok

;;; L-Eval input:
(define (id x)
  (set! count (+ count 1))
  x)

;;; L-Eval value:
ok

;;; L-Eval input:
(define w (id (id 10)))

;;; L-Eval value:
ok

;;; L-Eval input:
count

;;; L-Eval value:
1

;;; L-Eval input:
w

;;; L-Eval value:
10

;;; L-Eval input:
count

;;; L-Eval value:
2

;;; L-Eval input:

分析

因为所有的参数都会变成 trunks,所以

(id (id 10))

将会变成

(set! count (+ count 1))
(trunks (id 10) <env>)

w 即被绑定到 (trunks (id 10) <env>) 上了,这个时候因为有 (id 10) 没有运行而 count 只是 1。再对 w 求值的时候, (trunks (id 10) <env>) 被求值,w 被绑定到 10,而 count 增加了 1。得到结果 count 为 2。