Exercise 4.29. Exhibit a program that you would expect to run much more slowly without memoization than with memoization. Also, consider the following interaction, where the id procedure is defined as in exercise 4.27 and count starts at 0:
(define (square x)
(* x x))
;;; L-Eval input:
(square (id 10))
;;; L-Eval value:
<response>
;;; L-Eval input:
count
;;; L-Eval value:
<response>
Give the responses both when the evaluator memoizes and when it does not.
如果我们使用了 memoization,count 的结果将是 1;如果不使用,count 的结果将是 2。
使用 memoization 的时候,因为在调用 square 时,x 被绑定到 (trunk (id 10) env) 上。求 square 的值时,* 是 primitive procedure,所以将求 trunk 的值。而在第一次对 ( trunk (id 10) env) 求值之后,因为 memoization 的原因, env 中的 trunk 将被替换为 (id 10) 的值,这就导致了第二次 (id 10) 不会再运行 set! 而直接返回 10。count 只被改变了一次。
不使用 memoization 的时候,(id 10) 出现几次,它的过程体就会被求几次值。