Implement SubFunctionPattern
This commit is contained in:
parent
0a386c13f4
commit
75fe857139
@ -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);
|
||||||
|
}
|
||||||
|
}
|
@ -1,8 +1,30 @@
|
|||||||
package it.cavallium.warppi.math.rules.dsl;
|
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 org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class PatternTest {
|
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()));
|
||||||
|
}
|
||||||
}
|
}
|
Loading…
x
Reference in New Issue
Block a user