Aldo Calpini writes:
> I've taken this bison example (an RPN calculator, stripped down version
> from http://www.gnu.org/software/bison/manual/html_node/Rpcalc-Rules.html):
>
> input: /* empty */
> | input line
> ;
>
> line: '\n'
> | exp '\n'
> ;
>
> exp: NUM
> | exp exp '+'
> | exp exp '-'
> | exp exp '*'
> | exp exp '/'
> ;
> %%
>
> and this is my attempt at a "port" to Perl6:
>
> grammar RPN {
> rule input { <line>* }
> rule line { <exp>? \n }
> rule exp {
> [ NUM
> | <exp> <exp> <'+'>
> | <exp> <exp> <'-'>
> | <exp> <exp> <'*'>
> | <exp> <exp> <'/'>
> ]
> }
>
> rule NUM { \d+ } # could be more complex, I know :-)
> }
>
> if $data ~~ RPN.input { say "valid RPN data" }
>
> am I missing something obvious here? will the above code work in Perl6?
> do you have perhaps a better example, or just an idea about what to show?
Looks good. This doesn't grok whitespace, so it will accept:
3+4*5
But not
3 + 4 * 5
So you need to add a C<:w> modifier to your C<exp> rule.
Also, if this is going to be an explanation rather than just a picture,
I suggest you go with Perl's usual versatile power, and store the
operators in a declarative data source.
grammar RPN {
my @operator = << + - * / >>;
rule input { <line>* }
rule line { <exp>? \n }
rule exp :w{ <NUM> | <@operator> }
rule NUM { \d+ }
}
if $data ~~ /<RPN.input>/ { say "valid expression" }
Luke