Rules for drawing and interpreting environment diagrams

Environment Diagrams:

  • HAND THEM IN ON PAPER UNLESS YOU ARE PSYCHOTIC
  • When to draw a procedure object:

  • When a procedure is -define-d
  • If a -lambda- is returned
  • For -let-, do not bother drawing the procedure object, just draw the frame

    When to draw a frame:

  • Every time a procedure is invoked (this includes -let-)
  • However, for primitives such as +, don't bother

    When you draw a frame:

  • The frame must point back to the environment that the corresponding procedure object points to
    Example:
    (define (fact n)
      (fact-iter 1 n))
    (define (fact-iter result n)
       (cond ((< n 2) result)
             (else (fact-iter (* n result) (- n 1)))))
    (fact 4)
    

    In the above case:

    fact is defined in the global environment
  • fact-iter is also defined in the global environment
  • Therefore, the one call to fact and four calls to fact-iter will all point back to the global environment

    However, in the below case, fact-iter is defined inside fact and is thus not visible in the global environment. Its procedure object should be drawn hanging off the fact frame.

    (define (fact n)
      (define (fact-iter result n)
        (cond ((< n 2) result)
              (else (fact-iter (* n result) (- n 1)))))
      (fact-iter 1 n))
    (fact 4)
    

    Remember:

  • Environment diagrams show how state variables work by showing the *scope* of variables
  • Environment diagrams do NOT show the calling sequence of procedures