forked from kanaka/mal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep2_eval.hy
executable file
·64 lines (54 loc) · 1.68 KB
/
step2_eval.hy
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
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env hy
(import sys traceback)
(import [reader [read-str Blank]])
(import [printer [pr-str]])
;; read
(defn READ [str]
(read-str str))
;; eval
(defn eval-ast [ast env]
(if
(symbol? ast) (if (.has_key env ast) (get env ast)
(raise (Exception (+ ast " not found"))))
(instance? dict ast) (dict (map (fn [k]
[(EVAL k env) (EVAL (get ast k) env)])
ast))
(instance? tuple ast) (tuple (map (fn [x] (EVAL x env)) ast))
(instance? list ast) (list (map (fn [x] (EVAL x env)) ast))
True ast))
(defn EVAL [ast env]
;; indented to match later steps
(if (not (instance? tuple ast))
(eval-ast ast env)
;; apply list
(if
(empty? ast)
ast
;; apply
(do
(setv el (eval-ast ast env)
f (first el)
args (list (rest el)))
(apply f args)))))
;; print
(defn PRINT [exp]
(pr-str exp True))
;; repl
(def repl-env {'+ +
'- -
'* *
'/ (fn [a b] (int (/ a b)))})
(defn REP [str]
(PRINT (EVAL (READ str) repl-env)))
(defmain [&rest args]
;; indented to match later steps
(while True
(try
(do (setv line (raw_input "user> "))
(if (= "" line) (continue))
(print (REP line)))
(except [EOFError] (break))
(except [Blank])
(except []
(print (.join "" (apply traceback.format_exception
(.exc_info sys))))))))