CSE 341 -- Eval and Apply; Meta-circular Interpreters

eval

The eval function takes a Scheme object and an environment, and evaluates the Scheme object. Examples:
(define fn '*)
(define x 3)
(define y (list '+ x 5))
(define z (list fn 10 y))
x  =>  3
y  => (+ 3 5)
z  => (* 10 (+ 3 5))
(eval '(+ 6 6) user-initial-environment)  => 12
(eval y user-initial-environment)  => 8
(eval z user-initial-environment)  => 80
An example of variables whose values are atoms:
(define a 'b)
(define b 'c)
(define c 50)
a => b
(eval a user-initial-environment)  => c
(eval (eval a user-initial-environment) user-initial-environment)  => 50
The top level of the Scheme interpreter is a read-eval-print loop: read in an expression, evaluate it, and print the result.

user-initial-environment is bound to an environment and is pre-defined. There are also functions to get the environment for any procedure, etc. See the MIT Scheme User's Manual section on read-eval-print loop.

Quote suppresses evaluation; eval causes evaluation. They can cancel each other out.

(define x 3)
x  =>  3
'x => x
(eval 'x user-initial-environment)  => 3

apply

The apply function applies a function to a list of its arguments. Examples:
(apply factorial '(3))  => 6
(apply + '(1 2 3 4))  => 10
A useful programming trick is to use apply to define a function that takes a list of arguments, if you have available a function that arbitrary number of arguments. Example:
(define (sum s) (apply + s))
(sum '(1 2 3))  => 6

Metacircular Evaluators

Fundamental idea: "The evaluator, which determines the meaning of expressions in a language, is just another program."

Metacircular evaluator: an evaluator written in the same language it evaluates.

Reasons to look at metacircular evaluators: better understanding of language semantics; allows us to experiment with different semantics.

The evaluater presented here makes use of the underlying Scheme implementation to handle many details, such as garbage collection, storage allocation, etc. (See Chapter 5 for material on how to handle these issues.)