Skip to content

Commit 9382356

Browse files
committed
an abstract reduction tool for re-association
1 parent c9e22ce commit 9382356

File tree

2 files changed

+31
-15
lines changed

2 files changed

+31
-15
lines changed

lib/Parser/BOP.pm

+26
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,32 @@ sub swapOps {
302302
return $self;
303303
}
304304

305+
#
306+
# Change an association "(a bop b) bop c" to "a bop (b bop c)" or vice versa
307+
# argument $dir should be 'left' or 'right'
308+
# 'left' for "a bop (b bop c)" to become "(a bop b) bop c"
309+
# 'right' for "(a bop b) bop c" to become "a bop (b bop c)"
310+
# Assumes the calling entity verified it is appropriate to associate
311+
#
312+
sub associateOps {
313+
my $self = shift;
314+
my $dir = shift;
315+
if ($dir eq 'left') {
316+
return $self->Item('BOP')->new(
317+
$self->{equation}, $self->{bop},
318+
$self->Item('BOP')->new($self->{equation}, $self->{bop}, $self->{lop}, $self->{rop}{lop})->reduce,
319+
$self->{rop}{rop}
320+
)->reduce;
321+
} else {
322+
return $self->Item('BOP')->new(
323+
$self->{equation},
324+
$self->{lop}{bop},
325+
$self->{lop}{lop},
326+
$self->Item('BOP')->new($self->{equation}, $self->{bop}, $self->{lop}{rop}, $self->{rop})
327+
)->reduce;
328+
}
329+
}
330+
305331
#
306332
# Get the variables from the two operands
307333
#

lib/Parser/BOP/multiply.pm

+5-15
Original file line numberDiff line numberDiff line change
@@ -68,21 +68,11 @@ sub _reduce {
6868
$self->swapOps
6969
if (($self->{rop}->class eq 'Number' && $self->{lop}->class ne 'Number' && $reduce->{'x*n'})
7070
|| ($self->{lop}->class eq 'Function' && $self->{rop}->class ne 'Function' && $reduce->{'fn*x'}));
71-
72-
if ($reduce->{'m*(n*x)'}
73-
&& defined $self->{lop}
74-
&& defined $self->{rop}{lop}
75-
&& defined $self->{rop}{bop}
76-
&& $self->{lop}->class eq 'Number'
77-
&& $self->{rop}{lop}->class eq 'Number'
78-
&& $self->{rop}{bop} eq '*')
79-
{
80-
my $m = $self->{lop};
81-
$self->{lop} = $self->{rop}->copy;
82-
$self->{lop}->swapOps;
83-
$self->{lop}{lop} = $m;
84-
$self->{rop} = $self->{rop}{rop};
85-
}
71+
$self = $self->associateOps('left')
72+
if ($reduce->{'m*(n*x)'}
73+
&& $self->{lop}->class eq 'Number'
74+
&& $self->{rop}->isa('Parser::BOP::multiply')
75+
&& $self->{rop}{lop}->class eq 'Number');
8676
return $self;
8777
}
8878

0 commit comments

Comments
 (0)