Make NegativePattern match and produce negative numbers
This commit is contained in:
parent
d18e2d3708
commit
df5de92931
@ -3,9 +3,11 @@ package it.cavallium.warppi.math.rules.dsl.patterns;
|
||||
import it.cavallium.warppi.math.Function;
|
||||
import it.cavallium.warppi.math.MathContext;
|
||||
import it.cavallium.warppi.math.functions.Negative;
|
||||
import it.cavallium.warppi.math.functions.Number;
|
||||
import it.cavallium.warppi.math.rules.dsl.Pattern;
|
||||
import it.cavallium.warppi.math.rules.dsl.VisitorPattern;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
@ -26,12 +28,28 @@ public class NegativePattern extends VisitorPattern {
|
||||
return inner.match(negative.getParameter());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Map<String, Function>> visit(final Number number) {
|
||||
final BigDecimal value = number.getTerm();
|
||||
if (value.signum() < 0) {
|
||||
return inner.match(new Number(number.getMathContext(), value.abs()));
|
||||
} else {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function replace(final MathContext mathContext, final Map<String, Function> subFunctions) {
|
||||
return new Negative(
|
||||
mathContext,
|
||||
inner.replace(mathContext, subFunctions)
|
||||
);
|
||||
final Function newInner = inner.replace(mathContext, subFunctions);
|
||||
|
||||
if (newInner instanceof Number) {
|
||||
return ((Number) newInner).multiply(new Number(mathContext, -1));
|
||||
} else {
|
||||
return new Negative(
|
||||
mathContext,
|
||||
inner.replace(mathContext, subFunctions)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -111,13 +111,28 @@ public class PatternTest {
|
||||
|
||||
final Function shouldMatch = new Negative(
|
||||
mathContext,
|
||||
new Number(mathContext, 2)
|
||||
new Variable(mathContext, 'x', Variable.V_TYPE.VARIABLE)
|
||||
);
|
||||
final Optional<Map<String, Function>> subFunctions = pattern.match(shouldMatch);
|
||||
assertTrue(subFunctions.isPresent());
|
||||
assertEquals(shouldMatch, pattern.replace(mathContext, subFunctions.get()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void negativePatternForNumber() {
|
||||
final Pattern pattern = new NegativePattern(
|
||||
new NumberPattern(new BigDecimal(1))
|
||||
);
|
||||
|
||||
final Function shouldNotMatch = new Number(mathContext, 1);
|
||||
assertFalse(pattern.match(shouldNotMatch).isPresent());
|
||||
|
||||
final Function shouldMatch = new Number(mathContext, -1);
|
||||
final Optional<Map<String, Function>> subFunctions = pattern.match(shouldMatch);
|
||||
assertTrue(subFunctions.isPresent());
|
||||
assertEquals(shouldMatch, pattern.replace(mathContext, subFunctions.get()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void undefinedPattern() {
|
||||
final Pattern pattern = new UndefinedPattern();
|
||||
|
Loading…
Reference in New Issue
Block a user