Implement ConstantPattern

This commit is contained in:
Riccardo Azzolini 2018-11-20 19:07:34 +01:00
parent 5238c32380
commit 26416dd8f8
2 changed files with 58 additions and 0 deletions

View File

@ -0,0 +1,36 @@
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.Variable;
import it.cavallium.warppi.math.rules.dsl.VisitorPattern;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Matches and generates a specific symbolic constant.
*/
public class ConstantPattern extends VisitorPattern {
private final char symbol;
public ConstantPattern(final char symbol) {
this.symbol = symbol;
}
@Override
public Optional<Map<String, Function>> visit(final Variable variable) {
if (variable.getType().equals(Variable.V_TYPE.CONSTANT)
&& variable.getChar() == symbol) {
return Optional.of(new HashMap<>());
} else {
return Optional.empty();
}
}
@Override
public Function replace(final MathContext mathContext, final Map<String, Function> subFunctions) {
return new Variable(mathContext, symbol, Variable.V_TYPE.CONSTANT);
}
}

View File

@ -2,6 +2,7 @@ package it.cavallium.warppi.math.rules.dsl;
import it.cavallium.warppi.math.Function;
import it.cavallium.warppi.math.MathContext;
import it.cavallium.warppi.math.MathematicalSymbols;
import it.cavallium.warppi.math.functions.*;
import it.cavallium.warppi.math.functions.Number;
import it.cavallium.warppi.math.functions.equations.Equation;
@ -188,6 +189,27 @@ public class PatternTest {
assertEquals(rootSquare, replacement);
}
@Test
public void constantPattern() {
final Pattern pattern = new ConstantPattern(MathematicalSymbols.PI);
final Function shouldNotMatch = new Variable(
mathContext,
MathematicalSymbols.EULER_NUMBER,
Variable.V_TYPE.CONSTANT
);
assertFalse(pattern.match(shouldNotMatch).isPresent());
final Function shouldMatch = new Variable(
mathContext,
MathematicalSymbols.PI,
Variable.V_TYPE.CONSTANT
);
final Optional<Map<String, Function>> subFunctions = pattern.match(shouldMatch);
assertTrue(subFunctions.isPresent());
assertEquals(shouldMatch, pattern.replace(mathContext, subFunctions.get()));
}
@Test
public void otherBinaryPatterns() {
final Number one = new Number(mathContext, 1);