CSE 341 -- Eval and Apply

eval

In DrScheme, the eval function takes a Scheme object, and evaluates the Scheme object. (It can also take a second argument, which is an environment. This is actually what is specified in the R5 spec.) 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))  => 12
(eval y)  => 8
(eval z)  => 80
An example of variables whose values are atoms:
(define a 'b)
(define b 'c)
(define c 50)
a => b
(eval a)  => c
(eval (eval a))  => 50
The top level of the Scheme interpreter is a read-eval-print loop: read in an expression, evaluate it, and print the result. See read-eval-print implementation.

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

(define x 3)
x  =>  3
'x => x
(eval 'x)  => 3

Using the Environment Argument to eval

(eval '(+ 3 4) (scheme-report-environment 5))  => 7
(eval '(+ 3 4) (null-environment 5))  => error!

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

Example read-eval-print Function

(downloadable version of read-eval-print function)
(define (read-eval-print)
  (display "read-eval-print here")
  (newline)
  (display "type done to exit")
  (newline)
  (let ((r (read)))
    (newline)
    (display "input: ")
    (display r)
    (newline)
    (if (eq? r 'done)
        (display "bye!")
        (begin
          (display "result: ")
          (print (eval r))
          (newline)
          (read-eval-print)))))