6.001/Recitation 15

Rob Speer

Contents

The environment model

The EM is:

  • A way of graphically representing the state of the Scheme interpreter.
  • An explanation of how lexical scope works.
  • A way of showing on tests that you understand what a procedure is doing.

The rules

When you evaluate a lambda expression:

  • Create a "double bubble" to represent the procedure
  • The left bubble is the code pointer - it points down to a brief indication of what the procedure will do
  • The right bubble is the environment pointer - it points up to the current environment

When you apply a procedure:

  • Create a frame
  • Make this frame point to a parent frame, which is the same as the environment pointer of the procedure (not the current environment!)
  • Connect the two pointers to show where the frame came from
  • Bind the arguments of the procedure in this new frame
  • Evaluate the body of the procedure in the frame

Examples to work out

A smallish procedure that calls a helper function:

(define (silly x)
  (define (add-one y) (+ y 1))
  (* (add-one y) 2))

(silly 3)

And some borrowed from 6.001/Recitation 6:

(define make-count-proc-1
  (lambda (f)
    (lambda (x)
      (let ((count 0))
        (cond ((eq? x 'count) count)
              (else
               (set! count (+ count 1))
               (f x)))))))

(define sqrt* (make-count-proc-1 sqrt))
(sqrt* 4)
(sqrt* 'count)


(define make-count-proc-2
  (lambda (f)
    (let ((count 0))
      (lambda (x)
        (cond ((eq? x 'count) count)
              (else
               (set! count (+ count 1))
               (f x)))))))

(define sqrt* (make-count-proc-2 sqrt))
(define square* (make-count-proc-2 square))
(sqrt* 4)
(sqrt* 'count)
(square* 4)
(square* 'count)


(define make-count-proc-3
  (let ((count 0))
    (lambda (f)
      (lambda (x)
        (cond ((eq? x 'count) count)
              (else
               (set! count (+ count 1))
               (f x)))))))

(define sqrt* (make-count-proc-2 sqrt))
(define square* (make-count-proc-2 square))
(sqrt* 4)
(sqrt* 'count)
(square* 4)
(square* 'count)

I wish I could draw environment diagrams in this handout

Now, a couple of examples to show that a pointer to a lambda doesn't always come from that lambda's environment.