Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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.

A good way to do this is via OO, representing your operation types as subclasses:

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->op, map { $_->display($self->precedence) } $self->children; $s = "($s)" if $precedence > $self->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] }
Then you just call the display method on an Op tree. For example,
Op::Multiplication->new( Op::Term->new(5), Op::Addition->new( Op::Term->new(6), Op::Term->new(7) ) )->display; # 5 * (6 + 7) Op::Addition->new( Op::Term->new(5), Op::Multiplication->new( Op::Term->new(6), Op::Term->new(7) ) )->display; # 5 + 6 * 7
And you can see how easy it would be to add new types of operations, due to the beauty of subclassing.

blokhead


In reply to Re^2: Using overload to parse arithmetic terms by blokhead
in thread Using overload to parse arithmetic terms by esskar

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-03-28 09:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found