灯下 登录
计算机科学 / SICP / 3.1.1 Local State Variables

Exercise 3.2 · 习题

Exercise 3.2: In software-testing applications,
it is useful to be able to count the number of times a given procedure is
called during the course of a computation. Write a procedure
make-monitored that takes as input a procedure, f, that itself
takes one input. The result returned by make-monitored is a third
procedure, say mf, that keeps track of the number of times it has been
called by maintaining an internal counter. If the input to mf is the
special symbol how-many-calls?, then mf returns the value of the
counter. If the input is the special symbol reset-count, then mf
resets the counter to zero. For any other input, mf returns the result
of calling f on that input and increments the counter. For instance, we
could make a monitored version of the sqrt procedure:

(define s (make-monitored sqrt))

(s 100)
10

(s 'how-many-calls?)

1

练习 3.2:在软件测试应用中,统计某个过程在一次计算过程中被调用的次数往往很有用。请编写一个过程 make-monitored,它以一个过程 f 为输入,f 本身接受一个输入。make-monitored 返回的结果是第三个过程,设为 mf,它通过维护一个内部计数器来跟踪自己被调用的次数。若传给 mf 的输入是特殊符号 how-many-calls?,则 mf 返回计数器的当前值。若输入是特殊符号 reset-count,则 mf 将计数器重置为零。对于任何其他输入,mf 返回以该输入调用 f 的结果,并将计数器加一。例如,我们可以创建 sqrt 过程的一个受监控版本:

(define s (make-monitored sqrt))

(s 100)
10

(s 'how-many-calls?)
1

Racket #lang sicp
(define s (make-monitored sqrt))

(s 100)
10

(s 'how-many-calls?)
1