CS 22
Clab 17: The Environment Model
Our goal will be to master the environment model of
evaluation. The key material is the bulleted items on
pages 238 and 240.
- To evaluate a combination:
1. Evaluate the subexpressions of the
combination.
2. Apply the value of the operator subexpression
to the values of the
operand subexpressions.
The environment model of procedure application can be summarized by
two rules:
- A procedure object is applied to a set of arguments by
constructing a frame, binding the formal parameters of the procedure
to the arguments of the call, and then evaluating the body of
the procedure in the context of the new environment constructed. The
new frame has as its enclosing environment the environment part of the
procedure object being applied.
- A procedure is created by evaluating a lambda
expression relative to a given environment. The resulting procedure
object is a pair consisting of the text of the lambda expression
and a pointer to the environment in which the procedure was created.
We will slowly go through section
3.2.
(define (square x) (* x x))
Syntactic sugar for:
(define square
(lambda (x) (* x x)))
The function definitions below are also syntactic sugar for lambda
expressions.
(define (sum-of-squares x y)
(+ (square x) (square y)))
(define (f a)
(sum-of-squares (+ a 1) (* a 2)))
Let's build the procedure objects and then evaluate:
(f 5)
illustrating the environments constructed during the evaluation.
Now you do ex 3.9 for the recursive version showing the
environment structures created by evaluating
(factorial 4).
If I think there is time, we'll go over the environment construction
for the sequence below. In any case, you can review it at home.
(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 200))
(W1 50)