in reply to Convert stack-based code to "conventional" (was Re: Graphing SQLite's VDBE)
in thread Graphing SQLite's VDBE
OK ... I've toyed around with the code and did a version with the extra parenthesis removal. Here ya go:
Which gives us:#!/usr/bin/perl -w use strict; use warnings; my @stack = (); sub binop { my $op = shift; my $prec = shift; my $lh = pop @stack; my ($lhop, $lhprec) = ($$lh[0], $$lh[1]); my $rh = pop @stack; my ($rhop, $rhprec) = ($$rh[0], $$rh[1]); # Wrap operand(s) with lower precedence $lhop = '(' . $lhop . ')' if $prec > $lhprec; $rhop = '(' . $rhop . ')' if $prec > $rhprec; push @stack, [ $lhop . $op . $rhop, $prec ]; } while (<DATA>) { chomp; print "TOS='" . (@stack ? $stack[$#stack][0] : '-nil-') . "' " . "stmt = '" . $_ . "'\n"; my ($operator, $operand) = split; if ($operator eq 'push') { # A constant is atomic, so it has high precedence so # we don't wrap it push @stack, [$operand, 999]; } elsif ($operator eq 'print') { my $op = pop @stack; my ($operand, $prec) = ($$op[0], $$op[1]); print "out: '" . $operand . "'\n"; } elsif ($operator eq 'add') { binop '+', 1; } elsif ($operator eq 'mul') { binop '*', 2; } } __DATA__ push 3 push 5 add push 7 push 9 add mul print
--roboticusroot@swill ~/PerlMonks $ ./stack_to_infix2.pl TOS='-nil-' stmt = 'push 3' TOS='3' stmt = 'push 5' TOS='5' stmt = 'add' TOS='5+3' stmt = 'push 7' TOS='7' stmt = 'push 9' TOS='9' stmt = 'add' TOS='9+7' stmt = 'mul' TOS='(9+7)*(5+3)' stmt = 'print' out: '(9+7)*(5+3)' root@swill ~/PerlMonks $
P.S. I don't like my code for getting arguments off the stack, but all my attempts at simplifying it failed miserably. I'm sure it's something simple, but I haven't figured it out. What's a better way to do the following? (Or is my problem a bit earlier and I'm pushing the wrong thing on the stack?)
my $op = pop @stack; my ($operand, $prec) = ($$op[0], $$op[1]);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Convert stack-based code to "conventional" (was Re: Graphing SQLite's VDBE)
by johngg (Canon) on Jan 24, 2007 at 15:35 UTC | |
|
Re^2: Convert stack-based code to "conventional" (was Re: Graphing SQLite's VDBE)
by roboticus (Chancellor) on Jan 25, 2007 at 03:24 UTC |