|
9 | 9 | ; Function names changed to ALL-CAPS to avoid potential |
10 | 10 | ; confusion with functions provided by Racket. |
11 | 11 |
|
| 12 | +(define (EVAL exp environ) |
| 13 | + ;; dispatch on expression type |
| 14 | + (cond [(number? exp) exp] ; self-evaluating |
| 15 | + [(symbol? exp) |
| 16 | + (LOOKUP-VARIABLE-VALUE exp environ)] |
| 17 | + [else |
| 18 | + (apply (EVAL (car exp) environ) ; operator |
| 19 | + (LIST-OF-VALUES (cdr exp) ; operands |
| 20 | + environ))])) |
| 21 | + |
| 22 | + |
| 23 | +(define (LIST-OF-VALUES exps environ) |
| 24 | + (if (null? exps) |
| 25 | + '() |
| 26 | + (cons (EVAL (car exps) environ) |
| 27 | + (LIST-OF-VALUES (cdr exps) environ)))) |
| 28 | + |
| 29 | +(define (EXTEND-ENVIRONMENT vars values base-environ) |
| 30 | + (cons (MAKE-FRAME vars values) base-environ)) |
| 31 | + |
| 32 | +(define (MAKE-FRAME vars values) |
| 33 | + (cond [(and (null? vars) (null? values)) '()] |
| 34 | + [(null? vars) (error "Too many arguments" values)] |
| 35 | + [(null? values) (error "Too few arguments" vars)] |
| 36 | + [else |
| 37 | + (cons (cons (car vars) (car values)) ; make binding |
| 38 | + (MAKE-FRAME (cdr vars) (cdr values)))])) |
| 39 | + |
| 40 | +(define (LOOKUP-VARIABLE-VALUE var environ) |
| 41 | + (if (null? environ) |
| 42 | + (error "Unbound variable" var) |
| 43 | + (let ([binding (ASSQ var (car environ))]) ; look in first frame |
| 44 | + (if (eq? binding #f) |
| 45 | + (LOOKUP-VARIABLE-VALUE var (cdr environ)) |
| 46 | + (cdr binding))))) |
| 47 | + |
12 | 48 | (define (ASSQ var bindings) |
13 | 49 | (cond [(null? bindings) #f] |
14 | 50 | [(eq? var (caar bindings)) (car bindings)] |
15 | 51 | [else (ASSQ var (cdr bindings))])) |
16 | 52 |
|
17 | | -(define (LOOKUP-VARIABLE-VALUE var env) |
18 | | - (if (null? env) |
19 | | - (error "Unbound variable" var) |
20 | | - (let ([binding (ASSQ var (car env))]) |
21 | | - (if (eq? binding #f) |
22 | | - (LOOKUP-VARIABLE-VALUE var (cdr env)) |
23 | | - (cdr binding))))) |
| 53 | +(define (MAKE-BUILTINS) |
| 54 | + (EXTEND-ENVIRONMENT |
| 55 | + '(+ - * /) |
| 56 | + (list + - * /) |
| 57 | + '())) |
24 | 58 |
|
25 | 59 | ; Needed to support rackunit tests in concrete-test.rkt. |
26 | 60 | (provide ASSQ |
27 | | - LOOKUP-VARIABLE-VALUE) |
| 61 | + LOOKUP-VARIABLE-VALUE |
| 62 | + EXTEND-ENVIRONMENT |
| 63 | + MAKE-FRAME |
| 64 | + EVAL |
| 65 | + MAKE-BUILTINS) |
0 commit comments