matlab: step7, fix reader bug.
[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 'cell'
14 ret = {};
15 for i=1:length(ast)
16 ret{end+1} = EVAL(ast{i}, env);
17 end
18 otherwise
19 ret = ast;
20 end
21 end
22
23 function ret = EVAL(ast, env)
24 if ~iscell(ast),
25 ret = eval_ast(ast, env);
26 return;
27 end
28
29 % apply
30 el = eval_ast(ast, env);
31 f = el{1};
32 args = el(2:end);
33 ret = f(args{:});
34 end
35
36 % print
37 function ret = PRINT(ast)
38 ret = printer.pr_str(ast, true);
39 end
40
41 % REPL
42 function ret = rep(str, env)
43 ret = PRINT(EVAL(READ(str), env));
44 end
45
46 function main(args)
47 repl_env = containers.Map();
48 repl_env('+') = @(a,b) a+b;
49 repl_env('-') = @(a,b) a-b;
50 repl_env('*') = @(a,b) a*b;
51 repl_env('/') = @(a,b) floor(a/b);
52
53 %cleanObj = onCleanup(@() disp('*** here1 ***'));
54 while (true)
55 line = input('user> ', 's');
56 if strcmp(strtrim(line),''), continue, end
57 try
58 fprintf('%s\n', rep(line, repl_env));
59 catch err
60 fprintf('Error: %s\n', err.message);
61 fprintf('%s\n', getReport(err, 'extended'));
62 end
63 end
64 end