Presentation is loading. Please wait.

Presentation is loading. Please wait.

Defining New Special Forms (unless test body) (if (not test) body #f) (when (not test) body)

Similar presentations


Presentation on theme: "Defining New Special Forms (unless test body) (if (not test) body #f) (when (not test) body)"— Presentation transcript:

1 Defining New Special Forms (unless test body) (if (not test) body #f) (when (not test) body)

2 (inc! x) (set! x (inc x))

3 (define unless (method ((test ) (body )) (if (not test) body #f))) (define inc! (method ((x )) (set! x (inc x)))) doesn't work!

4 Macros Ordinary functions 1. Evaluate the arguments 2. Apply function to (values of) the arguments 3. Return the result of step 2 Macros 1. Substitute the (unevaluated) args textually in the body 2. Evaluate the result 3. Return the result of step 2.

5 class special form macro (macro (params) pre-body) 1. The pre-body is evaluated twice : once to do the textual substitution and once to compute the value. 2. The first evaluation is done in the environment of the closure, the second is done in the environment of the call.

6 Want (inc! z) to expand to (set! z (inc z)) (define (inc! ) (macro (x) (list 'set! x (list 'inc x))))

7 (define (inc! ) (macro (x) (list 'set! x (list 'inc x)))) pre-body

8 1. Evaluate the pre-body in the environment of the closure with params bound to unevaluated arguments 2. Evaluate the resulting expression in the environment of the macro call.

9 (define (inc! ) (macro (x) (list 'set! x (list 'inc x)))) (define z 3) => 3 (inc! z) => (set! z (inc z)) => 4 z => 4

10 (define (unless ) (macro (tst bdy) (list 'if (list 'not tst) bdy '#f))) (define x 2) => 2 (unless (= x 0) (/ 2 x)) => (if (not (= x 0)) (/ 2 x) #f) => 1

11 EVALUATION (define-generic-function brenda-eval ((obj ) (env ))) (add-method brenda-eval (method ((obj ) (env )) obj)) (add-method brenda-eval (method ((obj ) (env )) (lookup obj env))) (add-method brenda-eval (method ((obj ) (env )) (brenda-apply (brenda-eval (head obj) env) (tail obj) env)))

12 APPLICATION (define-generic-function brenda-apply ((obj ) (args ) (env ))) (add-method brenda-apply (method ((obj ) (args ) (env )) ((calls obj) args env))) (add-method brenda-apply (method ((obj ) (args ) (e )) (bind (((evaled-args ) (map (method (x) (brenda-eval x e)) args))) (when (args-params-match? (params obj) evaled-args) (bind ((new-env (expand-environment (params obj) evaled-args (env obj)))) (eval-sequence (body obj) new-env))))))

13 MACROS (add-method brenda-apply (method ((obj ) (args ) (e )) (when (args-params-match? (params obj) args) (bind ((new-env (expand-environment (params obj) args (env obj)))) (brenda-eval (eval-sequence (body obj) new-env) e)))))


Download ppt "Defining New Special Forms (unless test body) (if (not test) body #f) (when (not test) body)"

Similar presentations


Ads by Google