make-monitored 要完成四件事:
f 以及一个计数局部变量 count-call'how-many-calls? 时,返回 count-call 的值'reset-count 时,将 count-call 的值重置为 0 。'how-many-calls ,也不是 'reset-count ,那么将 count-call 的数值加一,并使用输入调用函数 f以下是 make-monitored 函数的定义:
;;; 2-make-monitored.scm
(define (make-monitored f)
(let ((count-call 0))
(lambda (input)
(cond ((eq? input 'how-many-calls?)
count-call)
((eq? input 'reset-count)
(begin (set! count-call 0)
count-call))
(else (begin (set! count-call (+ 1 count-call))
(f input)))))))
测试:
1 ]=> (load "2-make-monitored.scm")
;Loading "2-make-monitored.scm"... done
;Value: make-monitored
1 ]=> (define s (make-monitored sqrt))
;Value: s
1 ]=> (s 100)
;Value: 10
1 ]=> (s 'how-many-calls?)
;Value: 1
1 ]=> (s 9)
;Value: 3
1 ]=> (s 99)
;Value: 9.9498743710662
1 ]=> (s 'how-many-calls?)
;Value: 3
1 ]=> (s 'reset-count)
;Value: 0
1 ]=> (s 'how-many-calls?)
;Value: 0