SICP Exercise 3.11 make-account internal definitions with local state

Exercise 3.11.  In section 3.2.3 we saw how the environment model described the behavior of procedures with local state. Now we have seen how internal definitions work. A typical message-passing procedure contains both of these aspects. Consider the bank account procedure of section 3.1.1:

(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)


Show the environment structure generated by the sequence of interactions

(define acc (make-account 50))

((acc 'deposit) 40)
90

((acc 'withdraw) 60)
30


Where is the local state for acc kept? Suppose we define another account

(define acc2 (make-account 100))

How are the local states for the two accounts kept distinct? Which parts of the environment structure are shared between acc and acc2?

Solution:

The attached pictures show the progression of the environment structure as the sequence of interactions happens as specified in this exercise.

Local state for 'acc' is kept in environment E1. Local state for 'acc2' is kept in environment E6.

acc and acc2 share the procedure definitions for 'withdraw', 'deposit' and 'dispatch'.

The github links are:

Page 1
Page 2
Page 3
Page 4
Page 5

The slides to the same diagrams are here.









Comments

Popular posts from this blog

SICP Exercise 2.56 differentiation rule

SICP Exercise 1.28 (Miller-Rabin Test)

SICP Exercise 4.18 a alternative strategy for interpreting internal definitions