Skip to content

Commit

Permalink
Merge pull request #1025 from Alex-Jordan/reduce-mnx
Browse files Browse the repository at this point in the history
reduction rule for m(nx)->(mn)x
  • Loading branch information
drgrice1 authored Aug 6, 2024
2 parents beb20c5 + 9382356 commit 6b85f52
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
26 changes: 26 additions & 0 deletions lib/Parser/BOP.pm
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,32 @@ sub swapOps {
return $self;
}

#
# Change an association "(a bop b) bop c" to "a bop (b bop c)" or vice versa
# argument $dir should be 'left' or 'right'
# 'left' for "a bop (b bop c)" to become "(a bop b) bop c"
# 'right' for "(a bop b) bop c" to become "a bop (b bop c)"
# Assumes the calling entity verified it is appropriate to associate
#
sub associateOps {
my $self = shift;
my $dir = shift;
if ($dir eq 'left') {
return $self->Item('BOP')->new(
$self->{equation}, $self->{bop},
$self->Item('BOP')->new($self->{equation}, $self->{bop}, $self->{lop}, $self->{rop}{lop})->reduce,
$self->{rop}{rop}
)->reduce;
} else {
return $self->Item('BOP')->new(
$self->{equation},
$self->{lop}{bop},
$self->{lop}{lop},
$self->Item('BOP')->new($self->{equation}, $self->{bop}, $self->{lop}{rop}, $self->{rop})
)->reduce;
}
}

#
# Get the variables from the two operands
#
Expand Down
22 changes: 14 additions & 8 deletions lib/Parser/BOP/multiply.pm
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ sub _reduce {
$self->swapOps
if (($self->{rop}->class eq 'Number' && $self->{lop}->class ne 'Number' && $reduce->{'x*n'})
|| ($self->{lop}->class eq 'Function' && $self->{rop}->class ne 'Function' && $reduce->{'fn*x'}));
$self = $self->associateOps('left')
if ($reduce->{'m*(n*x)'}
&& $self->{lop}->class eq 'Number'
&& $self->{rop}->isa('Parser::BOP::multiply')
&& $self->{rop}{lop}->class eq 'Number');
return $self;
}

Expand All @@ -78,14 +83,15 @@ sub makeNeg {
return $self;
}

$Parser::reduce->{'1*x'} = 1;
$Parser::reduce->{'x*1'} = 1;
$Parser::reduce->{'0*x'} = 1;
$Parser::reduce->{'x*0'} = 1;
$Parser::reduce->{'(-x)*y'} = 1;
$Parser::reduce->{'x*(-y)'} = 1;
$Parser::reduce->{'x*n'} = 1;
$Parser::reduce->{'fn*x'} = 1;
$Parser::reduce->{'1*x'} = 1;
$Parser::reduce->{'x*1'} = 1;
$Parser::reduce->{'0*x'} = 1;
$Parser::reduce->{'x*0'} = 1;
$Parser::reduce->{'(-x)*y'} = 1;
$Parser::reduce->{'x*(-y)'} = 1;
$Parser::reduce->{'x*n'} = 1;
$Parser::reduce->{'fn*x'} = 1;
$Parser::reduce->{'m*(n*x)'} = 1;

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

0 comments on commit 6b85f52

Please sign in to comment.