<?xml version="1.0" encoding="windows-1252"?>
<node id="528524" title="Re^2: Using overload to parse arithmetic terms" created="2006-02-07 09:41:52" updated="2006-02-07 04:41:52">
<type id="11">
note</type>
<author id="137386">
blokhead</author>
<data>
<field name="doctext">
To expand (and generalize) on this a bit, let each type of operation have a precedence. Then as you walk the expression tree, you need to parenthesize operations that have a lower precedence than the expression they appear within.


&lt;p&gt;

A good way to do this is via OO, representing your operation types as subclasses:

&lt;code&gt;
package Op;
sub new {
    my $pkg = shift;
    bless [@_], $pkg;
}
sub children { @{ $_[0] } }
sub display {
    my ($self, $precedence) = @_;
    $precedence = 0 if not defined $precedence;
    my $s = join $self-&gt;op,
            map { $_-&gt;display($self-&gt;precedence) } $self-&gt;children;
    $s = "($s)" if $precedence &gt; $self-&gt;precedence;
    return $s;
}

package Op::Addition;
@ISA = qw[Op];
sub precedence { 10 }
sub op { " + " }

package Op::Multiplication;
@ISA = qw[Op];
sub precedence { 20 }
sub op { " * " }

# ...

package Op::Term;
@ISA = qw[Op];
sub precedence { 100 }
sub display { $_[0][0] }
&lt;/code&gt;

Then you just call the &lt;tt&gt;display&lt;/tt&gt; method on an Op tree. For example,

&lt;code&gt;
Op::Multiplication-&gt;new(
  Op::Term-&gt;new(5),
  Op::Addition-&gt;new(
    Op::Term-&gt;new(6),
    Op::Term-&gt;new(7)
  )
)-&gt;display;
# 5 * (6 + 7)

Op::Addition-&gt;new(
  Op::Term-&gt;new(5),
  Op::Multiplication-&gt;new(
    Op::Term-&gt;new(6),
    Op::Term-&gt;new(7)
  )
)-&gt;display;
# 5 + 6 * 7
&lt;/code&gt;

And you can see how easy it would be to add new types of operations, due to the beauty of subclassing.

&lt;!-- Node text goes above. Div tags should contain sig only --&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-137386"&gt;
&lt;p&gt;
blokhead
&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
528475</field>
<field name="parent_node">
528498</field>
</data>
</node>
