vb: add seq and string?
[jackhill/mal.git] / julia / step2_eval.jl
1 #!/usr/bin/env julia
2
3 push!(LOAD_PATH, pwd(), "/usr/share/julia/base")
4 import readline_mod
5 import reader
6 import printer
7
8 # READ
9 function READ(str)
10 reader.read_str(str)
11 end
12
13 # EVAL
14 function eval_ast(ast, env)
15 if typeof(ast) == Symbol
16 env[ast]
17 elseif isa(ast, Array) || isa(ast, Tuple)
18 map((x) -> EVAL(x,env), ast)
19 elseif isa(ast, Dict)
20 [EVAL(x[1],env) => EVAL(x[2], env) for x=ast]
21 else
22 ast
23 end
24 end
25
26 function EVAL(ast, env)
27 if !isa(ast, Array) return eval_ast(ast, env) end
28
29 # apply
30 el = eval_ast(ast, env)
31 f, args = el[1], el[2:end]
32 f(args...)
33 end
34
35 # PRINT
36 function PRINT(exp)
37 printer.pr_str(exp)
38 end
39
40 # REPL
41 repl_env = Dict{Any,Any}(:+ => +,
42 :- => -,
43 :* => *,
44 :/ => div)
45 function REP(str)
46 return PRINT(EVAL(READ(str), repl_env))
47 end
48
49 while true
50 line = readline_mod.do_readline("user> ")
51 if line === nothing break end
52 try
53 println(REP(line))
54 catch e
55 if isa(e, ErrorException)
56 println("Error: $(e.msg)")
57 else
58 println("Error: $(string(e))")
59 end
60 bt = catch_backtrace()
61 Base.show_backtrace(STDERR, bt)
62 println()
63 end
64 end