Class 3: More on evaluation

This class will be held in the location of our labs, MI 302.

Slides

Display version (pdf)

UPDATE: eval in definitions vs. interactions

DrScheme can do some strange things. If you type (eval '(+ 1 2)) in the interactions (bottom) window, you will get back 3, as expected. However, if you type the exact same expression, (eval '(+ 1 2)), into the definitions window, DrScheme gives an error basically saying that + is undefined. What gives?

The long answer is documented here (note: this is technically the documentation for a later version of Scheme called Racket, but the exposition is better than in the documentation for our older version).

The short answer is that the definitions window actually creates a Scheme module, and the interactions window is executed outside of that module. So the behavior of eval is different because they are in different namespaces. Roughly speaking, eval can't see the bindings of the module it's currently in.

In case you actually do want to do something like this, there is a two-line fix:

  (define-namespace-anchor nsanchor)
  (define ns (namespace-anchor->namespace nsanchor))
Putting this in the definitions window just attaches a name - ns - to the module's namespace. Then you can pass this namespace to eval and something like
(eval '(+ 1 2) ns)
will actually work - in either window.

(Try to remember this when we talk about namespaces from the point of view of the compiler in a few weeks.)

Reference Reading

These readings are not required; however, they will be very useful to review this material and/or gain more depth.

Handouts

Homework

Reading: SICP Section 1.3. (You can skip the unnumbered subsections on the half-interval method, Newton's method, etc.)

Exercises: Code up solutions to exercises 1 and 2 and print them out. Add your written solution to #3 and hand in all three as a hard copy. Due at the beginning of class on Friday.

  1. Write a function (make-adder n) that returns a function (lambda expression) which takes one argument and adds n to it.
    So for instance ((make-adder 5) 3)8.
  2. Write a function (double f) which takes a 1-argument function f and produces a one-argument function (lambda expression) that takes an argument x and produces (f (f x)). So for instance (double sqrt) produces a function to find 4th roots.
  3. Are we allowed to say (double double)? What does it produce?