Lab 4: Bindings and simple evaluation

 

This lab will focus on using symbols. Use the Pretty Big language in Dr.Scheme.

A binding is a data structure with two elements, a key and a value. Its constructor and selectors might look like this:

(define (make-binding key value) (list key value))

(define (key binding) (car binding))

(define (value binding) (cadr binding))

Example:

(define b1 (make-binding 'bob 42))

(key b1) --> bob

(value b1) --> 42

An environment is a list of bindings:

(define environment1 (list (make-binding 'bob 42)

                           (make-binding 'cindy 13)))

Exercise 1: Write a function lookup that takes a key and an environment and returns the  first binding with a matching key. If no binding is found, return #f. For example:

(lookup 'cindy environment1) --> (cindy 13)

(lookup 'greg environment1) --> #f

Exercise 2: Write a function myeval that takes any legal scheme combination using the "+" operator with only 2 arguments, and an environment, and computes the value of the combination. There are three cases: either the combination is a symbol, in which case the result is its binding value, or the combination is +, in which case the result is the sum of the results of evaluating the 2 arguments, or you may signal an error. For example:
(myeval 'bob environment1) --> 42
(myeval '(+ bob bob) environment1) --> 84
(myeval '(+ bob (+ cindy cindy)) environment1) --> 68
(myeval '(+ (+ bob bob) (+ (+ bob cindy) cindy)) environment1) --> 152

Exercise 3: Write a new function lookup2 that takes a key and a list of environments and returns the  first binding with a matching key in the first environment. If no binding is found, return #f. For example:

   (define env1 (list (make-binding 'bob 42)

                      (make-binding 'cindy 13)))

   (define env2 (list (make-binding 'marsha 22)

                      (make-binding 'cindy 5)))

 

(lookup2 'cindy (list env1 env2)) --> (cindy 13)

(lookup2 'cindy (list env2 env1)) --> (cindy 5)

(lookup2 'marsha (list env1 env2)) --> (marsha 22)

(lookup2 'greg (list env1 env2)) --> #f

Congratulations. You have just implemented Scheme's lexical scoping. Think of env2 as the Global Environment, and env1 is a local environment created on the fly by binding the FORMAL parameters of a function to the ACTUAL values passed in. When you EVAL the body of the function, you LOOKUP in the formal parameter bindings, env1, before looking in the global bindings. That's basically what happens for real!