Skip to content
Browse files

Add Reverse Polish Notation calculator.

  • Loading branch information...
1 parent 8aa2faf commit 33fdbb7fd20fbeb0fa867abe0146fbd7cfd749c9 Daniel Carrera committed Jun 6, 2009
Showing with 40 additions and 0 deletions.
  1. +40 −0 interpreters/RPN.pl
  2. 0 {acme → interpreters}/brainfuck.p6.pl
View
40 interpreters/RPN.pl
@@ -0,0 +1,40 @@
+# Reverse Polish Notation Calculator.
+#
+# Copyright 2009 Daniel Carrera
+# This is free software. You can use it under the terms of Perl itself.
+#
+# USAGE: perl6 RPN.pl "5 4 + 3 / 5 3 - *"
+
+token Op { '+' || '-' || '*' || '/' };
+token Value { \d+[\.\d+]? };
+token Item { <Value> || <Op> };
+token Expr { [<Item> <ws>]+ };
+
+my $str = @*ARGS[0];
+
+if $str ~~ /^ <Expr> $/ {
+ my @stack;
+
+ for $/<Expr><Item> -> $item {
+ if $item<Value> {
+ @stack.push($item<Value>);
+ } else {
+ my $v1 = @stack.pop;
+ my $v0 = @stack.pop;
+ @stack.push(do_op($v0,$v1,$item<Op>));
+ }
+ }
+ say @stack[0];
+} else {
+ say "This is not an RPN expression.";
+}
+
+
+sub do_op($lhs, $rhs, $op) {
+ given $op {
+ when '*' { $lhs * $rhs }
+ when '+' { $lhs + $rhs }
+ when '-' { $lhs - $rhs }
+ when '/' { $lhs / $rhs }
+ }
+}
View
0 acme/brainfuck.p6.pl → interpreters/brainfuck.p6.pl
File renamed without changes.

0 comments on commit 33fdbb7

Please sign in to comment.
Something went wrong with that request. Please try again.