Merge pull request #217 from dubek/lua-interop
[jackhill/mal.git] / mal / step3_env.mal
CommitLineData
31690700
JM
1(load-file "../mal/env.mal")
2
3;; read
4(def! READ (fn* [strng]
5 (read-string strng)))
6
7
8;; eval
9(def! eval-ast (fn* [ast env] (do
10 ;;(do (prn "eval-ast" ast "/" (keys env)) )
11 (cond
12 (symbol? ast) (env-get env ast)
13
14 (list? ast) (map (fn* [exp] (EVAL exp env)) ast)
15
16 (vector? ast) (apply vector (map (fn* [exp] (EVAL exp env)) ast))
17
18 (map? ast) (apply hash-map
19 (apply concat
20 (map (fn* [k] [k (EVAL (get ast k) env)])
21 (keys ast))))
22
23 "else" ast))))
24
25(def! LET (fn* [env args]
26 (if (> (count args) 0)
27 (do
28 (env-set env (nth args 0) (EVAL (nth args 1) env))
29 (LET env (rest (rest args)))))))
30
31(def! EVAL (fn* [ast env] (do
32 ;;(do (prn "EVAL" ast "/" (keys @env)) )
33 (if (not (list? ast))
34 (eval-ast ast env)
35
36 ;; apply list
37 (let* [a0 (first ast)]
38 (cond
3178009c
DM
39 (nil? a0)
40 ast
41
31690700
JM
42 (= 'def! a0)
43 (env-set env (nth ast 1) (EVAL (nth ast 2) env))
44
45 (= 'let* a0)
46 (let* [let-env (new-env env)]
47 (do
48 (LET let-env (nth ast 1))
49 (EVAL (nth ast 2) let-env)))
50
51 "else"
52 (let* [el (eval-ast ast env)
53 f (first el)
54 args (rest el)]
55 (apply f args))))))))
56
57
58;; print
59(def! PRINT (fn* [exp] (pr-str exp)))
60
61;; repl
62(def! repl-env (new-env))
63(def! rep (fn* [strng]
1617910a 64 (PRINT (EVAL (READ strng) repl-env))))
31690700 65
8cb5cda4
JM
66(env-set repl-env "+" +)
67(env-set repl-env "-" -)
68(env-set repl-env "*" *)
69(env-set repl-env "/" /)
31690700 70
86b689f3
JM
71;; repl loop
72(def! repl-loop (fn* []
31690700
JM
73 (let* [line (readline "mal-user> ")]
74 (if line
75 (do
76 (if (not (= "" line))
77 (try*
86b689f3 78 (println (rep line))
31690700
JM
79 (catch* exc
80 (println "Uncaught exception:" exc))))
86b689f3
JM
81 (repl-loop))))))
82
83(def! -main (fn* [& args]
84 (repl-loop)))
31690700 85(-main)