;; Caltech CS1 Fall 2007
;; Scheme code used in Lecture 13 (11/12/07)
;; mvanier@cs.caltech.edu
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; New special form: set!
(define a 10) ; a is now 10
(set! a 20)   ; a changes to 20
(define astate 0)
(define (accum0! x)
  (set! astate (+ astate x)))
;; use
(accum0! 1)
astate  ; --> 1
(accum0! 1)
astate  ; --> 2
(accum0! 1)
astate  ; --> 3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define astate 0)
(define (accum! x)
  (begin
    (set! astate (+ astate x))
    astate))
;; use
(accum! 1) ; --> 1
(accum! 1) ; --> 2
(accum! 1) ; --> 3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (sadd x y z)
  (begin
    (set! x (+ x y))
    (set! x (+ x z))
    x))
;; use
(sadd 1 2 3) ; --> 6
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Environment Model: four basic rules
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; 1) A "define" expression creates a new binding in the current
;;    environment's first frame.
;;
;; 2) A "set!" expression searches the current environment for a binding
;;    matching a particular name and changes the value of the binding to a
;;    new value.  It never creates a binding from scratch.
;;
;; 3) A "lambda" expression is a pair consisting of
;;    -- the text of the lambda expression (parameters + body)
;;    -- a pointer to the environment in which the lambda was 
;;       first evaluated
;;
;; 4) Applying a lambda expression to its argument list
;;    -- creates a new frame
;;    -- all the formal arguments of the lambda expression are bound to the
;;       corresponding (evaluated) arguments from the argument list
;;    -- the frame's parent environment is the same environment as the
;;       environment associated with the lambda
;;    -- the body of the lambda is evaluated in the context of the new 
;;       frame
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
