Skip to content

Commit 6b85f52

Browse files
authored
Merge pull request #1025 from Alex-Jordan/reduce-mnx
reduction rule for m(nx)->(mn)x
2 parents beb20c5 + 9382356 commit 6b85f52

File tree

2 files changed

+40
-8
lines changed

2 files changed

+40
-8
lines changed

lib/Parser/BOP.pm

Lines changed: 26 additions & 0 deletions
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

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +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+
$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');
7176
return $self;
7277
}
7378

@@ -78,14 +83,15 @@ sub makeNeg {
7883
return $self;
7984
}
8085

81-
$Parser::reduce->{'1*x'} = 1;
82-
$Parser::reduce->{'x*1'} = 1;
83-
$Parser::reduce->{'0*x'} = 1;
84-
$Parser::reduce->{'x*0'} = 1;
85-
$Parser::reduce->{'(-x)*y'} = 1;
86-
$Parser::reduce->{'x*(-y)'} = 1;
87-
$Parser::reduce->{'x*n'} = 1;
88-
$Parser::reduce->{'fn*x'} = 1;
86+
$Parser::reduce->{'1*x'} = 1;
87+
$Parser::reduce->{'x*1'} = 1;
88+
$Parser::reduce->{'0*x'} = 1;
89+
$Parser::reduce->{'x*0'} = 1;
90+
$Parser::reduce->{'(-x)*y'} = 1;
91+
$Parser::reduce->{'x*(-y)'} = 1;
92+
$Parser::reduce->{'x*n'} = 1;
93+
$Parser::reduce->{'fn*x'} = 1;
94+
$Parser::reduce->{'m*(n*x)'} = 1;
8995

9096
sub string {
9197
my ($self, $precedence, $showparens, $position, $outerRight) = @_;

0 commit comments

Comments
 (0)