Implement NegativePattern

This commit is contained in:
Riccardo Azzolini 2018-10-06 14:27:06 +02:00
parent 64553c86e7
commit 0afacf7ddc
2 changed files with 53 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package it.cavallium.warppi.math.rules.dsl.patterns;
import it.cavallium.warppi.math.Function;
import it.cavallium.warppi.math.functions.Negative;
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 the negative of another pattern.
*/
public class NegativePattern extends VisitorPattern {
private final Pattern inner;
public NegativePattern(Pattern inner) {
this.inner = inner;
}
@Override
public Optional<Map<String, Function>> visit(Negative negative) {
return inner.match(negative.getParameter());
}
@Override
public Function replace(Map<String, Function> subFunctions) {
return new Negative(
null,
inner.replace(subFunctions)
);
}
}

View File

@ -1,9 +1,11 @@
package it.cavallium.warppi.math.rules.dsl;
import it.cavallium.warppi.math.Function;
import it.cavallium.warppi.math.functions.Negative;
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.rules.dsl.patterns.NegativePattern;
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;
@ -92,4 +94,22 @@ public class PatternTest {
assertTrue(subFunctions.isPresent());
assertEquals(shouldMatch, pattern.replace(subFunctions.get()));
}
@Test
public void negativePattern() {
final Pattern pattern = new NegativePattern(
new SubFunctionPattern("x")
);
final Function shouldNotMatch = new Number(null, 1);
assertFalse(pattern.match(shouldNotMatch).isPresent());
final Function shouldMatch = new Negative(
null,
new Number(null, 2)
);
final Optional<Map<String, Function>> subFunctions = pattern.match(shouldMatch);
assertTrue(subFunctions.isPresent());
assertEquals(shouldMatch, pattern.replace(subFunctions.get()));
}
}