fREWdiculous!
3 Mar
Apparently Patrick Michaud, pumpking of rakudo, read my post yesterday and he came up with an even better solition!
I’d read his post if I were you, but here was the code he got it down to (after adding the R meta op
):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | my %op_dispatch_table = { '+' => { .push(.pop + .pop) }, '-' => { .push(.pop R- .pop) }, '*' => { .push(.pop * .pop) }, '/' => { .push(.pop R/ .pop) }, 'sqrt' => { .push(.pop.sqrt) }, }; sub evaluate (%odt, $expr) { my @stack; my @tokens = $expr.split(/\s+/); for @tokens { when /\d+/ { @stack.push($_); } when ?%odt{$_} { %odt{$_}(@stack); } default { die "Unrecognized token '$_'; aborting"; } } @stack.pop; } say "Result: { evaluate(%op_dispatch_table, @*ARGS[0]) }"; |
Brilliant!
2 Responses for "Reverse Polish Notation Calculator in Perl6++"
“solution”
It becomes even more Perl 6′ish if you replace $expr.split(/\s+/); with $expr.comb;
Cheers,
Moritz
Leave a reply