State, Assignment and the Environment Model
The environment model (SICP 3.2): an environment is a sequence of frames, each mapping variables to values and pointing to an enclosing environment. Evaluating lambda creates a procedure object pointing to the current environment; applying it creates a new frame extending that environment. This explains closures, lexical scope, and how set! affects shared variables.
Mutable data (SICP 3.3): queues, tables, digital-circuit simulators, and constraint propagation built with set-car!/set-cdr!.
;; set! introduces state and time
(define balance 100)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(withdraw 25) ; 75
(withdraw 25) ; 50: same call, different result → no longer referentially transparent
;; Encapsulated state with closures
(define (make-withdraw balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds")))
(define w1 (make-withdraw 100))
(define w2 (make-withdraw 100))
(w1 50) ; 50
(w2 70) ; 30: independent state
;; Monte Carlo estimation of pi with a random-number generator
(define (monte-carlo trials experiment)
(let loop ((remaining trials) (passed 0))
(cond ((= remaining 0) (/ passed trials))
((experiment) (loop (- remaining 1) (+ passed 1)))
(else (loop (- remaining 1) passed)))))
;; (random is implementation-specific: Guile/Chez/Racket provide (random n); SRFI-27 is portable);; A queue with front and rear pointers
(define (make-queue) (cons '() '()))
(define (empty-queue? q) (null? (car q)))
(define (insert-queue! q item)
(let ((new (list item)))
(if (empty-queue? q)
(begin (set-car! q new) (set-cdr! q new))
(begin (set-cdr! (cdr q) new) (set-cdr! q new)))
q))
(define (delete-queue! q) (set-car! q (cdr (car q))) q)
(define (front-queue q) (car (car q)))
(define q (make-queue))
(insert-queue! q 'a) (insert-queue! q 'b)
(front-queue q) ; a