Fix empty list eval in step2 for most languages.
[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 if isempty(ast) return ast end
29
30 # apply
31 el = eval_ast(ast, env)
32 f, args = el[1], el[2:end]
33 f(args...)
34 end
35
36 # PRINT
37 function PRINT(exp)
38 printer.pr_str(exp)
39 end
40
41 # REPL
42 repl_env = Dict{Any,Any}(:+ => +,
43 :- => -,
44 :* => *,
45 :/ => div)
46 function REP(str)
47 return PRINT(EVAL(READ(str), repl_env))
48 end
49
50 while true
51 line = readline_mod.do_readline("user> ")
52 if line === nothing break end
53 try
54 println(REP(line))
55 catch e
56 if isa(e, ErrorException)
57 println("Error: $(e.msg)")
58 else
59 println("Error: $(string(e))")
60 end
61 bt = catch_backtrace()
62 Base.show_backtrace(STDERR, bt)
63 println()
64 end
65 end