Reverse Polish Notation Calculator in Perl6++

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 :-) ):

    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!

Posted Tue, Mar 3, 2009

If you're interested in being notified when new posts are published, you can subscribe here; you'll get an email once a week at the most.