2013年6月28日金曜日

開発環境

計算機プログラムの構造と解釈(Gerald Jay Sussman(原著)、Julie Sussman(原著)、Harold Abelson(原著)、和田 英一(翻訳)、ピアソンエデュケーション、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の3(標準部品化力, オブジェクトおよび状態)、3.1(代入と局所状態)、3.1.1(局所状態変数)の問題 3.1、問題 3.2、問題 3.3を解いてみる。

その他参考書籍

問題 3.1

コード(BBEdit)

sample.scm

(define (make-accumulator sum)
  (lambda (a)
    (begin (set! sum (+ sum a)) sum)))

(define A (make-accumulator 5))

入出力結果(Terminal, REPL(Read, Eval, Print, Loop))

1 ]=> (A 10)

;Value: 15

1 ]=> (A 10)

;Value: 25

問題 3.2

コード(BBEdit)

sample.scm

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

(define s (make-monitored sqrt))

入出力結果(Terminal, REPL(Read, Eval, Print, Loop))

1 ]=> (s 100)

;Value: 10

1 ]=> (s 'how-many-calls?)

;Value: 1

1 ]=> (s 100)        

;Value: 10

1 ]=> (s 'how-many-calls?)

;Value: 2

1 ]=> (define t (make-monitored sqrt))

;Value: t

1 ]=> (t 'how-many-calls?)

;Value: 0

1 ]=> (s 'reset-count)

;Value: 0

1 ]=> (s 'how-many-calls?)

;Value: 0

問題 3.3

コード(BBEdit)

sample.scm

(define (make-account balance secret-password)
  (define (withdraw amount)
    (if (>= balance amount)
        (begin (set! balance (- balance amount))
               balance)
        "Insufficient funds"))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (define (dispatch password m)
    (if (eq? secret-password password)
        (cond ((eq? m 'withdraw) withdraw)
              ((eq? m 'deposit) deposit)
              (else (error "Unkown request -- MAKE-ACCOUNT"
                                  m)))
        (lambda (a) "Incorrect password")))
  dispatch)

(define acc (make-account 100 'secret-password))

入出力結果(Terminal, REPL(Read, Eval, Print, Loop))

1 ]=> ((acc 'secret-password 'withdraw) 40)

;Value: 60

1 ]=> ((acc 'some-other-password 'deposit) 50)

;Value 2: "Incorrect password"

0 コメント:

コメントを投稿