Exercise3-1 <---> Exercise3-3
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
Ru: Русский текст упражнения
Scheme solution:
(define (make-monitored f)
(let ((count 0))
(lambda (arg)
(cond
((eq? arg 'how-many-calls?) count)
((eq? arg 'reset-count) (set! count 0) count)
(else (set! count (+ count 1))
(f arg))))))
In a slightly different ('dispatch') style, as per the text:
(define (make-monitored f)
(let ((count 0))
(define (reset-count) (begin (set! count 0) count))
(define (call-f m)
(begin (set! count (+ 1 count))
(f m)))
(define (mf m)
(cond ((eq? m 'how-many-calls?) count)
((eq? m 'reset-count) (reset-count))
(else (call-f m))))
mf))
OCaml solution:
Probably the best way to do this is to use objects:
let make_monitored f =
object
val mutable count = 0
method how_many_calls = count
method reset_count = count <- 0; count
method call x = count <- count + 1; f x
end
Example:
# let s = make_monitored sqrt;; val s : < call : float -> float; how_many_calls : int; reset_count : int > = <obj> # s#call 100.;; - : float = 10. # s#how_many_calls;; - : int = 1
Exercise3-1 <---> Exercise3-3
Comments
| Can anyone showme how to do this problem in Dispatch way? Like the one on page 223 in the book. | ||||
| Posted by ckc-111-124 at 2008-10-21 11:34:28 X | ||||
I think it depends on the scheme implementations used, some permit let before define while others don't. | ||||
| Posted by 86 at 2009-07-14 15:46:00 X | ||||
I've added a Scheme example of the message passing with a named procedure (here 'mf' instead of 'dispatch') which works in MIT and PLT Scheme. | ||||
| Posted by AnonymousIV at 2009-07-21 15:06:57 | ||||