Skip to content

Instantly share code, notes, and snippets.

@jkeenan
Created May 14, 2016 11:57
Show Gist options
  • Save jkeenan/0ea11b45f75ec72fca82f665a5a8951a to your computer and use it in GitHub Desktop.
Save jkeenan/0ea11b45f75ec72fca82f665a5a8951a to your computer and use it in GitHub Desktop.
Bennett Todd's 'rpn' calculator program
#!/usr/bin/env perl6
use v6;
use fatal;
sub rpn (Str $line, @stack) returns Array {
for $line.words {
#say 'Debug ' ~ @stack.perl ~ $_;
when $_ ~~ /\d/ { @stack.push( +($_)); };
my $top = @stack.pop() if @stack;
my $next = @stack.pop() if @stack;
when '+' { @stack.push($next + $top) };
when '-' { @stack.push($next - $top) };
when '*' { @stack.push($next * $top) };
when '/' { @stack.push($next / $top) };
}
return @stack;
}
sub MAIN {
my @s = ();
while get() -> $l {
@s = rpn $l, @s;
print @s ~ ' ' if @s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment