Implement SubFunctionPattern

This commit is contained in:
Riccardo Azzolini 2018-10-05 22:14:27 +02:00
parent 0a386c13f4
commit 75fe857139
2 changed files with 53 additions and 0 deletions

View File

@ -0,0 +1,31 @@
package it.cavallium.warppi.math.rules.dsl.patterns;
import it.cavallium.warppi.math.Function;
import it.cavallium.warppi.math.rules.dsl.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Matches and generates any function as a named sub-function.
*/
public class SubFunctionPattern implements Pattern {
private final String name;
public SubFunctionPattern(String name) {
this.name = name;
}
@Override
public Optional<Map<String, Function>> match(Function function) {
HashMap<String, Function> subFunctions = new HashMap<>();
subFunctions.put(name, function);
return Optional.of(subFunctions);
}
@Override
public Function replace(Map<String, Function> subFunctions) {
return subFunctions.get(name);
}
}

View File

@ -1,8 +1,30 @@
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.Sum;
import it.cavallium.warppi.math.rules.dsl.patterns.SubFunctionPattern;
import org.junit.Test;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.*;
public class PatternTest {
@Test
public void subFunctionPattern() {
final Pattern pattern = new SubFunctionPattern("x");
final Function func = new Sum(
null,
new Number(null, 1),
new Number(null, 2)
);
final Optional<Map<String, Function>> subFunctions = pattern.match(func);
assertTrue(subFunctions.isPresent());
assertEquals(func, pattern.replace(subFunctions.get()));
}
}