Implement NumberPattern
This commit is contained in:
parent
5450d67497
commit
64553c86e7
@ -0,0 +1,35 @@
|
||||
package it.cavallium.warppi.math.rules.dsl.patterns;
|
||||
|
||||
import it.cavallium.warppi.math.Function;
|
||||
import it.cavallium.warppi.math.functions.Number;
|
||||
import it.cavallium.warppi.math.rules.dsl.VisitorPattern;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Matches and generates a specific number.
|
||||
*/
|
||||
public class NumberPattern extends VisitorPattern {
|
||||
private final BigDecimal value;
|
||||
|
||||
public NumberPattern(BigDecimal value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Map<String, Function>> visit(Number number) {
|
||||
if (number.getTerm().compareTo(value) == 0) {
|
||||
return Optional.of(new HashMap<>());
|
||||
} else {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function replace(Map<String, Function> subFunctions) {
|
||||
return new Number(null, value);
|
||||
}
|
||||
}
|
@ -4,11 +4,12 @@ import it.cavallium.warppi.math.Function;
|
||||
import it.cavallium.warppi.math.functions.Number;
|
||||
import it.cavallium.warppi.math.functions.Subtraction;
|
||||
import it.cavallium.warppi.math.functions.Sum;
|
||||
import it.cavallium.warppi.math.functions.Variable;
|
||||
import it.cavallium.warppi.math.rules.dsl.patterns.NumberPattern;
|
||||
import it.cavallium.warppi.math.rules.dsl.patterns.SubFunctionPattern;
|
||||
import it.cavallium.warppi.math.rules.dsl.patterns.SumPattern;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@ -78,4 +79,17 @@ public class PatternTest {
|
||||
);
|
||||
assertFalse(pattern.match(shouldNotMatch).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void numberPattern() {
|
||||
final Pattern pattern = new NumberPattern(BigDecimal.valueOf(Math.PI));
|
||||
|
||||
final Function shouldNotMatch = new Number(null, 2);
|
||||
assertFalse(pattern.match(shouldNotMatch).isPresent());
|
||||
|
||||
final Function shouldMatch = new Number(null, Math.PI);
|
||||
final Optional<Map<String, Function>> subFunctions = pattern.match(shouldMatch);
|
||||
assertTrue(subFunctions.isPresent());
|
||||
assertEquals(shouldMatch, pattern.replace(subFunctions.get()));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user