{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

notes41 - The substitute procedure is essentially the...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
Here is a one-screenful version of a Scheme interpreter, using the substitution model, with most of the details left out: ;;;;; In file cs61a/lectures/2.2/tiny.scm (define (scheme) (display "> ") (print (eval (read))) (scheme) ) (define (eval exp) (cond ((self-evaluating? exp) exp) ((symbol? exp) (look-up-global-value exp)) ((special-form? exp) (do-special-form exp)) (else (apply (eval (car exp)) (map eval (cdr exp)) )))) (define (apply proc args) (if (primitive? proc) (do-magic proc args) (eval (substitute (body proc) (formals proc) args)))) Although the versions we can actually run are bigger, this really does capture the essential structure of every Lisp interpreter, namely, a mutual recursion between eval (evaluate an expression) and apply (apply a function to arguments). To evaluate a procedure call means to evaluate the subexpressions recursively, then apply the car (a function) to the cdr (the arguments). To apply a function to arguments means to evaluate the body of the function with the argument values in place of the formal parameters.
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: The substitute procedure is essentially the substitute2 that you wrote in last week’s homework, except that it has to be a little more complicated to avoid substituting for quoted symbols and for the formal parameters of a lambda inside the body. What’s left out? Primitives, special forms, and a lot of details. The Scheme-1 interpreter has only three special forms: quote , if , and lambda . In particular, it doesn’t have define , so there are no global variables, and we can’t give procedures global names. If we need a name for a procedure, we have to use it as an argument to another procedure. In particular, if we want to write recursive procedures we have to use a trick that was an extra-for-experts in week 2: Scheme-1: ((lambda (n) ((lambda (f) (f f n)) ; the "Y combinator" (lambda (fact n) (if (= n 0) 1 (* n (fact fact (- n 1))) )) )) 5) 120 307...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online