SICP Exercise 3.10 make-withdraw with let

Exercise 3.10.  In the make-withdraw procedure, the local variable balance is created as a parameter of make-withdraw. We could also create the local state variable explicitly, using let, as follows:

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


Recall from section 1.3.2 that let is simply syntactic sugar for a procedure call:

(let ((<var> <exp>)) <body>)

is interpreted as an alternate syntax for

((lambda (<var>) <body>) <exp>)

Use the environment model to analyze this alternate version of make-withdraw, drawing figures like the ones above to illustrate the interactions

(define W1 (make-withdraw 100))

(W1 50)

(define W2 (make-withdraw 100))


Show that the two versions of make-withdraw create objects with the same behavior. How do the environment structures differ for the two versions?

Solution:

The attached pictures show the environment model for this version of make-withdraw. We can see that the environment E4 for W2 was created by the call to make-withdraw. It contains a frame with its own local binding for balance. On the other hand, W1 and W2 have the same code: the code specified by the Procedure Object 3. We see here why W1 and W2 behave as independent objects. Calls to W1 reference the state variable balance stored in E2, whereas calls to W2 reference the balance stored in E4. Thus, changes to the local state of one object do not affect the other object.

The github links are:


The google slides link to the same diagrams are:

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