University of Virginia, Department of Computer Science
CS200: Computer Science, Spring 2002

Notes: Friday 29 March 2002

Schedule
Lazy Evaluator
lazeval.ss
Code changes from meval.ss:
(define (thunk? expr) (tagged-list? expr 'thunk))
(define (make-thunk expr env) (list 'thunk expr env))
(define (thunk-expr thunk) (cadr thunk))
(define (thunk-env thunk) (caddr thunk))

(define (frame-lookup-name name frame)
  (if (null? frame) (error "Name not found in frame:" name)
      (if (eq? (car (car frame)) name) 
	  (car frame) ;;; was (cdr (car frame))
	  (frame-lookup-name name (cdr frame)))))

(define (environment-get-value! name env)
  (if (null? env) (error "No binding for" name)
      (if (frame-contains? name (first-frame env))
	  (let ((np (frame-lookup-name name (first-frame env))))
	    (if (thunk? (cdr np))
		(set-cdr! np (lazeval (thunk-expr (cdr np)) (thunk-env (cdr np)))))
	    (cdr np))
	  (environment-get-value! name (enclosing-environment env)))))

(define (lazapply procedure operands env)  
  (cond 
   ((primitive-procedure? procedure) 
    (lazapply-primitive procedure (map (lambda (op) (lazeval op env)) operands)))
   ((compound-procedure? procedure) 
    (lazeval-sequence
     (procedure-body procedure)
     (extend-environment
      (procedure-parameters procedure)
      (map (lambda (op) (make-thunk op env)) operands)
      (procedure-environment procedure))))
   (else (error "Unknown applicator: " procedure))))

(define (lazeval expr env)
  (cond
   ((self-evaluating? expr) expr)
   ((variable? expr)        (environment-get-value! expr env))
   ((lambda? expr)          (make-procedure (lambda-parameters expr) (lambda-body expr) env))
   ((definition? expr)      (define-variable! 
			      (definition-variable expr)
			      (lazeval (definition-value expr) env) env))
   ((application? expr)     (lazapply (lazeval (application-operator expr) env) 
				      (application-operands expr) env))
   (else                    (error "Unknown expression: " exp))))

Are there procedures we can define in a language with lazy evaluation, that cannot be defined in a language with eager evaluation?

I am no lazier now than I was forty years ago, but that is because I reached the limit forty years ago.
Mark Twain in Eruption

Bertrand Russel, In Praise of Idleness


CS 655 University of Virginia
Department of Computer Science
CS 200: Computer Science
David Evans
evans@virginia.edu
Using these Materials