Julia: add step2.
authorJoel Martin <github@martintribe.org>
Sun, 29 Mar 2015 19:33:57 +0000 (14:33 -0500)
committerJoel Martin <github@martintribe.org>
Wed, 1 Apr 2015 04:04:42 +0000 (23:04 -0500)
julia/step2_eval.jl [new file with mode: 0755]

diff --git a/julia/step2_eval.jl b/julia/step2_eval.jl
new file mode 100755 (executable)
index 0000000..ef08139
--- /dev/null
@@ -0,0 +1,67 @@
+#!/usr/bin/env julia
+
+import reader
+import printer
+
+# READ
+function READ(str)
+    reader.read_str(str)
+end
+
+# EVAL
+function eval_ast(ast, env)
+    if typeof(ast) == Symbol
+        env[ast]
+    elseif isa(ast, Array)
+        map((x) -> EVAL(x,env), ast)
+    else
+        ast
+    end
+end
+
+function EVAL(ast, env)
+    if !isa(ast, Array)
+        return eval_ast(ast, env)
+    end
+
+    # apply
+    el = eval_ast(ast, env)
+    f, args = el[1], el[2:end]
+    f(args...)
+end
+
+# PRINT
+function PRINT(exp)
+    printer.pr_str(exp)
+end
+
+# REPL
+repl_env = {:+ => +,
+            :- => -,
+            :* => *,
+            :/ => div}
+function REP(str)
+    return PRINT(EVAL(READ(str), repl_env))
+end
+
+while true
+    print("user> ")
+    flush(STDOUT)
+    line = readline(STDIN)
+    if line == ""
+        break
+    end
+    line = chomp(line)
+    try
+        println(REP(line))
+    catch e
+        if isa(e, ErrorException)
+            println("Error: $(e.msg)")
+        else
+            println("Error: $(string(e))")
+        end
+        bt = catch_backtrace()
+        Base.show_backtrace(STDERR, bt)
+        println()
+    end
+end