-
Notifications
You must be signed in to change notification settings - Fork 0
/
interp0.rkt
53 lines (45 loc) · 1.1 KB
/
interp0.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#lang racket
(define empty '())
(struct Closure
(param body env)
#:transparent)
(define extend
(lambda (env var value)
(cons `(var . value) env)))
(define lookup
(lambda (var env)
(cdr (assoc var env))))
(define getop
(lambda (name)
(match name
('+ +)
('- -)
('* *)
('/ /)
('< <)
('> >)
('+ +))))
(define literal?
(lambda (value)
(or (number? value)
(string? value))))
(define interp
(lambda (expr env)
(match expr
([? literal? x] x)
([? symbol? var] (lookup var env))
(`(lambda (,x) ,body) (Closure x body env))
(`(,op ,x ,y) ((getop op) (interp x env) (interp y env)))
(`(if ,a ,b ,c)
(if (interp a env)
(interp b env)
(interp c env))))))
(interp '3222 '())
(interp 'x '((x . 1)))
(interp '(+ x 1) '((x . 1)))
(interp '(- x 1) '((x . 2)))
(interp '(* x 1) '((x . 2)))
(interp '(/ x 1) '((x . 2)))
(interp '(lambda (x) (+ x 1)) '((x . 1)))
(interp '(lambda (x) (+ x 1)) '())
(interp '(if (> 3 2) 3 2) empty)