Commit | Line | Data |
---|---|---|
31690700 JM |
1 | ;; read |
2 | (def! READ (fn* [strng] | |
3 | (read-string strng))) | |
4 | ||
5 | ||
6 | ;; eval | |
7 | (def! eval-ast (fn* [ast env] (do | |
8 | ;;(do (prn "eval-ast" ast "/" (keys env)) ) | |
9 | (cond | |
01e8850d JM |
10 | (symbol? ast) (let* [res (get env (str ast))] |
11 | (if res res (throw (str ast " not found")))) | |
31690700 JM |
12 | |
13 | (list? ast) (map (fn* [exp] (EVAL exp env)) ast) | |
14 | ||
15 | (vector? ast) (apply vector (map (fn* [exp] (EVAL exp env)) ast)) | |
16 | ||
17 | (map? ast) (apply hash-map | |
18 | (apply concat | |
19 | (map (fn* [k] [k (EVAL (get ast k) env)]) | |
20 | (keys ast)))) | |
21 | ||
22 | "else" ast)))) | |
23 | ||
24 | ||
25 | (def! EVAL (fn* [ast env] (do | |
26 | ;;(do (prn "EVAL" ast "/" (keys @env)) ) | |
27 | (if (not (list? ast)) | |
28 | (eval-ast ast env) | |
29 | ||
30 | ;; apply list | |
efa2daef JM |
31 | (if (empty? ast) |
32 | ast | |
33 | (let* [el (eval-ast ast env) | |
34 | f (first el) | |
35 | args (rest el)] | |
36 | (apply f args))))))) | |
31690700 JM |
37 | |
38 | ||
39 | ||
40 | (def! PRINT (fn* [exp] (pr-str exp))) | |
41 | ||
42 | ;; repl | |
43 | (def! repl-env {"+" + | |
44 | "-" - | |
45 | "*" * | |
46 | "/" /}) | |
47 | (def! rep (fn* [strng] | |
1617910a | 48 | (PRINT (EVAL (READ strng) repl-env)))) |
31690700 | 49 | |
86b689f3 JM |
50 | ;; repl loop |
51 | (def! repl-loop (fn* [] | |
31690700 JM |
52 | (let* [line (readline "mal-user> ")] |
53 | (if line | |
54 | (do | |
55 | (if (not (= "" line)) | |
56 | (try* | |
86b689f3 | 57 | (println (rep line)) |
31690700 JM |
58 | (catch* exc |
59 | (println "Uncaught exception:" exc)))) | |
86b689f3 JM |
60 | (repl-loop)))))) |
61 | ||
62 | (def! -main (fn* [& args] | |
63 | (repl-loop))) | |
31690700 | 64 | (-main) |