练习 3.2

make-monitored 要完成四件事:

  1. 包装起输入的函数 f 以及一个计数局部变量 count-call
  2. 检查被包装函数的输入,当输入为 'how-many-calls? 时,返回 count-call 的值
  3. 检查被包装函数的输入,当输入为 'reset-count 时,将 count-call 的值重置为 0
  4. 如果输入既不是 '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

讨论

blog comments powered by Disqus