Toby Inkster avatar Toby Inkster committed b00625b Draft

add reverse polish notation calculator example

Comments (0)

Files changed (1)

examples/calculator.pl

+use feature qw( say );
+use Smart::Dispatch;
+
+{
+	my @stack;
+	my $eval = dispatcher {
+		match qr{\d+}, dispatch { push @stack, $_ };
+		match '+', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x + $y };
+		match '-', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x - $y };
+		match '*', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x * $y };
+		match '/', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x / $y };
+		match '%', dispatch { my ($x, $y) = splice(@stack, -2); push @stack, $x % $y };
+		otherwise failover { warn "Unknown token '$_'\n" };
+	};
+	sub reverse_polish_calc {
+		@stack = ();
+		$eval->($_) for @_;
+		wantarray ? @stack : $stack[-1];
+	}
+}
+
+
+# ( 1 + ((2+3)*4) ) - 5 = 16
+say reverse_polish_calc qw( 1 2 3 + 4 * + 5 - );
+
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.