15 hours ago
my attempt to do the exercises in sicp.
Wednesday, November 25, 2009
sicp exercise 3.10
; 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))
; "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?
; The procedure make-withdraw can be wrtten using alternate syntax for let as:
(define (make-withdraw initial-amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
"Insufficient funds"))) initial-amount))
The statement (define W1 (make-withdraw 100)) creates an environment E1, whose enclosing environment is global environment, in which initial-amount is bound to 100. When make-withdrawl gets executed, it evaluates the lambda procedure and creates an unnamed procedure whose arguments are balance and whose enclosing environment is E1. This procedure gets executed in E2 with balance bound to 100, and produces a procedure whose parameter is amount, this procedure points to environment E2. This procedure gets returned and is bound to W1 in the global environment.
The statement (W1 50) creates an environment E3 in which amount is bound to 50, this environment points to environment E2.
The statement (define W2 (make-withdraw 100)) will produce seperate environment (like E2) in which balance is bound to 100.
So balance and initial-amount for every make-withdraw is maintained in seperate environments.