LoginSignup
1
1

More than 5 years have passed since last update.

Perl 6 で逆ポ

Posted at

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";
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1