Open Source WEB

##(link2sicp "book-Z-H-20.html#%_thm_3.2" "Exercise 3.2")

解答例

(define (make-monitored func)
  (define mf 0)
  (define (how-many-calls?) mf)
  (define (reset-count) (set! mf 0) mf)
  (define (dispatch m)
    (cond ((eq? m 'how-many-calls?) (how-many-calls?))
          ((eq? m 'reset-count) (reset-count))
          (else (set! mf (+ 1 mf))
                (func m))))
  dispatch)

実行例

gosh>
(define s (make-monitored sqrt))
s
gosh> (s 'how-many-calls?)
0
gosh> (s 100)
10.0
gosh> (s 'how-many-calls?)
1
gosh> (s 9)
3.0
gosh> (s 'how-many-calls?)
2
gosh> (s 2500)
50.0
gosh> (s 'how-many-calls?)
3
gosh> (s 'reset-count)
0
gosh> (s 'how-many-calls?)
0
gosh> (s 100)
10.0
gosh> (s 'how-many-calls?)
1

--hidenao

コード

##(sicp-answer-code "ex-3.2.scm")

このサイトは、 IPA の「平成15年度オープンソフトウエア活用基盤整備事業」 の委託事業として開発されたKahuaで試験的に運用しております。

Copyright (c) 2004-2007 株式会社タイムインターメディア About Us