aboutsummaryrefslogtreecommitdiff
path: root/perl/step2_eval.pl
diff options
context:
space:
mode:
authorJoel Martin <github@martintribe.org>2014-04-20 21:50:52 -0500
committerJoel Martin <github@martintribe.org>2014-04-20 21:50:52 -0500
commita3b0621dbfbb7afd2bff5a08a727660142240150 (patch)
treefff280338345ca909166df2f586a637f5d846ce5 /perl/step2_eval.pl
parent9af8aee63aad6031c12f2b04ba87c16cc3273077 (diff)
downloadmal-a3b0621dbfbb7afd2bff5a08a727660142240150.tar.gz
mal-a3b0621dbfbb7afd2bff5a08a727660142240150.zip
Perl: add step2_eval.
Diffstat (limited to 'perl/step2_eval.pl')
-rw-r--r--perl/step2_eval.pl80
1 files changed, 80 insertions, 0 deletions
diff --git a/perl/step2_eval.pl b/perl/step2_eval.pl
new file mode 100644
index 0000000..c3910bd
--- /dev/null
+++ b/perl/step2_eval.pl
@@ -0,0 +1,80 @@
+use strict;
+use warnings;
+use readline qw(readline);
+use feature qw(switch);
+use Data::Dumper;
+
+use reader;
+use printer;
+
+# read
+sub READ {
+ my $str = shift;
+ return reader::read_str($str);
+}
+
+# eval
+sub eval_ast {
+ my($ast, $env) = @_;
+ given (ref $ast) {
+ when (/^Symbol/) {
+ if (exists $env->{$$ast}) {
+ return $env->{$$ast};
+ } else {
+ die "'" . $$ast . "' not found";
+ }
+ }
+ when (/^List/) {
+ my @lst = map {EVAL($_, $env)} @$ast;
+ return List->new(\@lst);
+ }
+ default {
+ return $ast;
+ }
+ }
+}
+
+sub EVAL {
+ my($ast, $env) = @_;
+ #print "EVAL: " . printer::_pr_str($ast) . "\n";
+ if (! ((ref $ast) =~ /^List/)) {
+ return eval_ast($ast, $env);
+ }
+
+ # apply list
+ my $el = eval_ast($ast, $env);
+ my $f = $el->[0];
+ return &{ $f }($el->rest());
+}
+
+# print
+sub PRINT {
+ my $exp = shift;
+ return printer::_pr_str($exp);
+}
+
+# repl
+my $repl_env = {};
+sub REP {
+ my $str = shift;
+ return PRINT(EVAL(READ($str), $repl_env));
+}
+
+$repl_env->{'+'} = sub { Integer->new(${$_[0][0]} + ${$_[0][1]}) };
+$repl_env->{'-'} = sub { Integer->new(${$_[0][0]} - ${$_[0][1]}) };
+$repl_env->{'*'} = sub { Integer->new(${$_[0][0]} * ${$_[0][1]}) };
+$repl_env->{'/'} = sub { Integer->new(${$_[0][0]} / ${$_[0][1]}) };
+
+while (1) {
+ my $line = readline("user> ");
+ if (! defined $line) { last; }
+ eval {
+ use autodie; # always "throw" errors
+ print(REP($line), "\n");
+ 1;
+ };
+ if (my $err = $@) {
+ chomp $err;
+ print "Error: $err\n";
+ }
+}