Implement SumPattern

This commit is contained in:
Riccardo Azzolini 2018-10-06 11:51:33 +02:00
parent 277589e7a9
commit 5450d67497
2 changed files with 90 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package it.cavallium.warppi.math.rules.dsl.patterns;
import it.cavallium.warppi.math.Function;
import it.cavallium.warppi.math.functions.Sum;
import it.cavallium.warppi.math.rules.dsl.Pattern;
import it.cavallium.warppi.math.rules.dsl.VisitorPattern;
import java.util.Map;
import java.util.Optional;
/**
* Matches and generates a sum of two other patterns.
*/
public class SumPattern extends VisitorPattern {
private final Pattern left;
private final Pattern right;
public SumPattern(Pattern left, Pattern right) {
this.left = left;
this.right = right;
}
@Override
public Optional<Map<String, Function>> visit(Sum sum) {
return left.match(sum.getParameter1())
.flatMap(leftMatch -> right.match(sum.getParameter2())
.flatMap(rightMatch -> mergeMatches(leftMatch, rightMatch))
);
}
@Override
public Function replace(Map<String, Function> subFunctions) {
return new Sum(
null,
left.replace(subFunctions),
right.replace(subFunctions)
);
}
}

View File

@ -2,8 +2,11 @@ package it.cavallium.warppi.math.rules.dsl;
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.SubFunctionPattern;
import it.cavallium.warppi.math.rules.dsl.patterns.SumPattern;
import org.junit.Test;
import java.util.Map;
@ -27,4 +30,52 @@ public class PatternTest {
assertEquals(func, pattern.replace(subFunctions.get()));
}
@Test
public void sumPattern() {
final Pattern pattern = new SumPattern(
new SubFunctionPattern("x"),
new SubFunctionPattern("y")
);
final Function shouldNotMatch = new Subtraction(
null,
new Number(null, 1),
new Number(null, 2)
);
assertFalse(pattern.match(shouldNotMatch).isPresent());
final Function shouldMatch = new Sum(
null,
new Number(null, 1),
new Number(null, 2)
);
final Optional<Map<String, Function>> subFunctions = pattern.match(shouldMatch);
assertTrue(subFunctions.isPresent());
assertEquals(shouldMatch, pattern.replace(subFunctions.get()));
}
@Test
public void repeatedSubFunction() {
final Pattern pattern = new SumPattern(
new SubFunctionPattern("x"),
new SubFunctionPattern("x")
);
final Function shouldMatch = new Sum(
null,
new Number(null, 1),
new Number(null, 1)
);
final Optional<Map<String, Function>> subFunctions = pattern.match(shouldMatch);
assertTrue(subFunctions.isPresent());
assertEquals(shouldMatch, pattern.replace(subFunctions.get()));
final Function shouldNotMatch = new Sum(
null,
new Number(null, 1),
new Number(null, 2)
);
assertFalse(pattern.match(shouldNotMatch).isPresent());
}
}