http://qiita.com/items/da7960c9ac1a15882ce2 に触発されて Perl 6 で逆ポーランド記法の計算機を書いた。オーソドックスに grammar を使っている。
use v6;
grammar RPN {
rule TOP { ^ [ <num> | <op> ]+ $ }
token num { <[\d.]>+ }
token op { < + - * / > }
}
sub rpn($rpn) {
RPN.parse($rpn, actions => class {
my @s;
method TOP($/) { make @s.pop }
method num($/) { @s.push: +$/ }
method op($/) { @s.push: +&::("infix:<$/>")(|[@s.pop, @s.pop].reverse) }
}).ast;
}
my $s = "
1 -> 1
1 2 + -> 3
3 1 - -> 2
10 2 / -> 5
2 5 8 + + -> 15
2 5 8 + * -> 26
2 5 8 * + -> 42
1 2 + 3 4 + * -> 21
2 3 * 4 5 * + -> 26
";
for $s.trim.lines {
$_ ~~ /(.+) ' -> ' (.+)/;
my $r = rpn(~$0);
say ($r == $1 ?? 'ok' !! 'fail') ~ ": $0 -> $r";
}