Re: Some random reflections on tpr05a

[email protected] (Rick Klement)
Newsgroups perl.golf
Message-ID <[email protected]>
[email protected] wrote:
> 
> If anyone has a working tpr05a solution using Parse::RecDescent
> or other CPAN module can you please post it to the list, as I
> am also interested in comparing that solution to the others.

You have only to ask:

This one uses Parse::Yapp.

Here's a rpn.y:

%left '+' '-'
%left '*' '/'

%%
expr:     NUMBER
        | '-' NUMBER      { "-$_[2]" }
        | expr '+' expr   { "$_[1] $_[3] +" }
        | expr '-' expr   { "$_[1] $_[3] -" }
        | expr '*' expr   { "$_[1] $_[3] *" }
        | expr '/' expr   { "$_[1] $_[3] /" }
        | '(' expr ')'    { $_[2] }
        ;
%%

my $s;          # warning - not re-entrant

sub yylex { $s=~/\G\d+/cg?('NUMBER',$&):$s=~/\G./cg?$&:'' }

sub parse
        {
        my $self = shift()->new(yylex=>\&yylex,
                yyerror=>sub{die "Syntax Error"});
        $s = shift;
        $self->YYParse;
        }

package main;           ###############################################

$_ = <>; s/\s+//g; print rpn->parse($_), "\n";



and a Makefile for it:

all: rpn.pl

rpn.pl: rpn.y
        yapp rpn.y
        echo '#!/usr/bin/perl' >rpn.pl
        cat rpn.pm >>rpn.pl
        chmod +x rpn.pl
        rm -f rpn.pm


that produces a rpn.pl that passes v8 tests: rpn.pl: 2807.26 strokes (ok)


Also, instead of using Parse::RecDescent, I did my own recursive
descent parser, and submitted it in the "Artistic" section at 141.36 (though
as the comment says, it's really a 137).


#!perl -p
sub o{print$"x$|++,shift}
sub f{s/^-*\d+//?o$&:e(s/.//)+s/.//}
sub t{f;o$&x1,f while s+^[*/]++}
sub e{t;o$&x1,t while s/^[+-]//}
e y/ 	//d


This would have scored in the middle of the pack, instead of the
actual depressing position I finished in.

-- 
Rick Klement
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.