When I gave up:

#! /usr/bin/env perl use v6; my %operators = ( '+' => sub { [+] @_ }, '-' => sub { [-] @_ }, '*' => sub { [*] @_ }, '/' => sub { [/] @_ }, ); grammar rpn_data { rule value { -?\d+ } rule operator { <[+*/\-]> } rule expression { } } sub rpn_eval (Str $e) returns Num { my @stack; # die "Invalid RPN: $e" unless $e ~~ /<expression>/; for $e.split() -> $tok { if $tok ~~ /<value> / { @stack.push($tok); next } @stack.push(%operators{$tok}(reverse @stack.pop, @stack.pop)); } @stack[0] } say rpn_eval($_) while $_ = =<>

For the most part, writing this was very exciting -- for the first time I delved into the perl6 rules stuff and tried to use it, and from this I now see how I would've solved this problem -- with code blocks after matches to neatly fail if I discovered improper RPN, or even with a modified %operators in the operator rule that evaluated the RPN as it was parsed.

And yet, this was disappointing: none of what I wanted to do was implemented in pugs.

Still, I've now a much better idea of what I've to look forward to. Thanks.

Update: in case anyone asks, there are no checks for overflow/underflow or such in my rpn_eval because I expected to have already verified that the RPN wouldn't have such problems. No point in uglyifying this test code with such checks when I discover that I momentarily can't. With time, I'll have this as the core of a real implementation.


In reply to Re: P6: Rule and RPN calc by ayrnieu
in thread P6: Rule and RPN calc by eric256

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.