Log in Page Discussion History Go to the site toolbox

3.2

From BluWiki

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
(define (make-monitored f)
  (define count 0)
  (define (how-many-calls?)
    count)
  (define (reset-count)
    (set! count 0))
  (define (dispatch m)
    (cond ((eq? m 'how-many-calls?) (how-many-calls?))
          ((eq? m 'reset-count) (reset-count))
          (else (begin
                  (set! count (+ 1 count))
                  (f m)))))
  dispatch)

;(define (func x) (* x x))
;(define mf (make-monitored func))
;(mf 'how-many-calls?)
;(mf 5)
;(mf 'how-many-calls?)
;(mf 3)
;(mf 'how-many-calls?)
;(mf 9)
;(mf 'how-many-calls?)
;(mf 'reset-count)
;(mf 'how-many-calls?)
;(mf 3)
;(mf 'how-many-calls?)

Site Toolbox:

Personal tools
GNU Free Documentation License 1.2
This page was last modified on 27 September 2007, at 20:51.
Disclaimers - About BluWiki