3.2.4 内部定義

Exercise 3.11

(define (make-account balance)
    (define (withdraw amount)
        (if 
            (>= balance amount)
            (begin (set! balance (- balance amount))
            balance)
        "Insufficient funds"))
    (define (deposit amount)
        (set! balance (+ balance amount))
        balance)
    (define (dispatch m)
        (cond 
            ((eq? m 'withdraw) withdraw)
            ((eq? m 'deposit) deposit)
        (else
            (error "Unknown request: MAKE-ACCOUNT"
        m))))
dispatch)

この手続が、次の対話によって生成される環境構造

(define acc (make-account 50))
((acc 'deposit) 40)
;90
((acc 'withdraw) 60)
;30

また、

(define acc2 (make-account 100))

を定義した時accとacc2の局所状態はどのようにして共有されるか?

自分の解答 f:id:cocodrips:20170925211657j:plain

なんか違いそうだった・・・。

解答ver2

exercise 3.11

(define (make-account balance)
    (define (withdraw amount)
        (if 
            (>= balance amount)
            (begin (set! balance (- balance amount)) balance)
            "Insufficient funds"
        )
    )

    (define (deposit amount)
        (set! balance (+ balance amount)) 
        balance
    )

    (define (dispatch m)
        (cond 
            ((eq? m 'withdraw) withdraw)
            ((eq? m 'deposit) deposit)
            (else
                (error "Unknown request: MAKE-ACCOUNT"
            m))
        )
    )
dispatch)

このプログラムが、次の対話によって⽣成される環境構造を⽰せ。

(define acc (make-account 50))
((acc 'deposit) 40)
((acc 'withdraw) 60)
(define acc2 (make-account 100))
  1. 初期状態

  2. (define acc (make-account 50))

  3. ((acc 'deposit) 40)

  4. ((acc 'withdraw) 60)

  5. (define acc2 (make-account 100)) .