You must write an Evaluator Definition to notify the Knowledge Builder's parser about the operator keyword and to provide the operator's implementation, for runtime. The Knowledge Builder may then be instantiated with a Knowledge Builder Configuration where this new Evaluator Definition is given as a Knowledge Builder option.
Here is a code snippet for the Knowledge Builder instantiation. All imports are from org.drools.builder and org.drools.builder.conf.
kBase = KnowledgeBaseFactory.newKnowledgeBase(); EvaluatorDefinition evDef = new appl.DisjointEvaluatorsDefinition(); MultiValueKnowledgeBuilderOption evOption = EvaluatorOption.get( "setop", evDef ); KnowledgeBuilderConfiguration kbConfig = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(); kbConfig.setOption( evOption ); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( kbConfig );
You can find the code for DisjointEvaluatorsDefinition here.
Here is a simple class containing a field to which the new operator disjoint can be applied.
public class Element { private String name; private Set<Integer> numbers; public Element( String name, Integer... numbers ){ ... } // getters... }Here is some Java code to create some Element facts.
for( Element element: new Element[]{ new Element( "primes", 2, 3, 5, 7, 11, 13, 17, 19 ), new Element( "even", 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ), new Element( "powers of 2", 1, 2, 4, 8, 16 ), new Element( "odd", 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 ), new Element( "esoteric", 7, 13 ) }{ session.insert( element ); }Now you can write rules such as the following:
rule "find disjoint pairs" when e1: Element( n1 : name, s1 : numbers ) e2: Element( this != e1, n2 : name, numbers disjoint s1 ) then System.out.println( n1 + " and " + n2 + " are disjoint."); end
If you compile and run everything, you should see the following output:
powers of 2 and esoteric are disjoint. even and esoteric are disjoint. esoteric and powers of 2 are disjoint. esoteric and even are disjoint. even and odd are disjoint. odd and even are disjoint.Notice that each matching pair of Element facts is reported twice. This is demonstrates that disjoint is a commutative operator.