Example environment diagrams in Scheme.
Example environment diagrams in Scheme.
Date Created:Saturday October 25th, 2008 05:26 PM
Date Modified:Tuesday January 19th, 2010 10:40 PM

(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 "what the?" m)))) dispatch)

(define acc (make-account 50))

((acc 'deposit) 40))

((acc 'withdraw) 60)


(define x 4)This sets a binding from x to the symbol 4.

(define (baz x) (define (* a b) (+ a b)) (lambda (y) (* x y)))This generates function bubbles that extends the global and binds the name baz to these bubbles. The left bubble points to the underlying code, the parameters and the body. The parameters in this case are x, and the body is the define and the lambda within the body of baz.

(define foo (baz (* 3 10)))Note that (* 3 10) is evaluated in the global, hence, it is tantamount to binding foo to (baz 30). This call, however, is more complex. First we need to initialize a new frame and bind some procedures, since baz is called: If you notice, first a new frame was created for the call to baz. The frame was initialized: 1) The frame was extended to the global since the right bubble of baz points to the global. 2) A binding for foo was set in the global and points to the lambda, the compound procedure returned by baz. This generates a pair of function bubbles with a parameter of y, and a body of (* x y). This function is an extension of the new frame. 3) A binding for x was set to 30, since the parameter for baz is x. 4) A binding for * was created within the new frame, along with a new function bubble pair for *, which extends this new frame as well.


