Implement NumberPattern

This commit is contained in:
Riccardo Azzolini 2018-10-06 14:01:29 +02:00
parent 5450d67497
commit 64553c86e7
2 changed files with 50 additions and 1 deletions

View File

@ -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);
}
}

View File

@ -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()));
}
}