matlab: fix empty list evaluation.
[jackhill/mal.git] / matlab / step2_eval.m
1 function step2_eval(varargin), main(varargin), end
2
3 % read
4 function ret = READ(str)
5 ret = reader.read_str(str);
6 end
7
8 % eval
9 function ret = eval_ast(ast, env)
10 switch class(ast)
11 case 'types.Symbol'
12 ret = env(ast.name);
13 case 'types.List'
14 ret = types.List();
15 for i=1:length(ast)
16 ret.append(EVAL(ast.get(i), env));
17 end
18 case 'types.Vector'
19 ret = types.Vector();
20 for i=1:length(ast)
21 ret.append(EVAL(ast.get(i), env));
22 end
23 case 'types.HashMap'
24 ret = types.HashMap();
25 ks = ast.keys();
26 for i=1:length(ks)
27 k = ks{i};
28 ret.set(EVAL(k, env), EVAL(ast.get(k), env));
29 end
30 otherwise
31 ret = ast;
32 end
33 end
34
35 function ret = EVAL(ast, env)
36 %fprintf('EVAL: %s\n', printer.pr_str(ast, true));
37 if ~type_utils.list_Q(ast)
38 ret = eval_ast(ast, env);
39 return;
40 end
41
42 % apply
43 if length(ast) == 0
44 ret = ast;
45 return;
46 end
47 el = eval_ast(ast, env);
48 f = el.get(1);
49 args = el.data(2:end);
50 ret = f(args{:});
51 end
52
53 % print
54 function ret = PRINT(ast)
55 ret = printer.pr_str(ast, true);
56 end
57
58 % REPL
59 function ret = rep(str, env)
60 ret = PRINT(EVAL(READ(str), env));
61 end
62
63 function main(args)
64 if exist('OCTAVE_VERSION', 'builtin') ~= 0
65 repl_env = Dict();
66 else
67 repl_env = containers.Map();
68 end
69 repl_env('+') = @(a,b) a+b;
70 repl_env('-') = @(a,b) a-b;
71 repl_env('*') = @(a,b) a*b;
72 repl_env('/') = @(a,b) floor(a/b);
73
74 %cleanObj = onCleanup(@() disp('*** here1 ***'));
75 while (true)
76 try
77 line = input('user> ', 's');
78 catch err
79 return
80 end
81 if strcmp(strtrim(line),''), continue, end
82 try
83 fprintf('%s\n', rep(line, repl_env));
84 catch err
85 fprintf('Error: %s\n', err.message);
86 type_utils.print_stack(err);
87 end
88 end
89 end