-
Notifications
You must be signed in to change notification settings - Fork 10
/
ex-3.2.scm
50 lines (42 loc) · 1.43 KB
/
ex-3.2.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
;;; 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
(define (make-monitored f)
(let ([called-count 0])
(lambda (x)
(cond
[(eq? x 'how-many-calls?)
called-count]
[(eq? x 'reset-count)
(set! called-count 0)]
[else
(set! called-count (+ called-count 1))
(f x)]))))
(define s (make-monitored sqrt))
(print (s 'how-many-calls?))
;=> 0
(print (s 100))
;=> 10
(print (s 16))
;=> 4
(print (s 'how-many-calls?))
;=> 2
(s 'reset-count)
(print (s 'how-many-calls?))
;=> 0