1
votes

This post suggests adding some fact classes as a way of nesting rules. http://drools.46999.n3.nabble.com/How-can-I-nested-rules-td4020488.html#a4020681

What I would like to know - is there a guarantee that "Age and gender women" executes before "Pregnant" and "Pregnant" before "Pregnant2"? As far I have noticed that is always the case in my application. But, is it documented somewhere in drools documentation or is it just the house of cards that is waiting to collapse?

    rule "Age and gender women" 
    when 
        $p : Person(p1 >= 12 && p2 = 1) 
    then 
        insertLogical( new CouldHaveBeenPregnant($p) ); 
end 

rule "Pregnant" 
    when 
        $p : Person(p3 > 1) 
        CouldHaveBeenPregnant( person == $p ) 
    then 
        insertLogical( new HasBeenPregnant($p) ); 
end 

rule "Pregnant2" 
    no-loop 
    when 
        $p : Person(p4 <= P3) 
        HasBeenPregnant( person == $p ) 
    then 
        $p.setStatus("OK"); 
        update($p); 
end 

Thanks for help in advance

EDIT: My problem arises when I have to add a new rule, say "not Pregnant", where I have to do something when person is NOT HasBeenPregnant( person == $p ). The inference principle doesn't work sometimes (as expected). Because, sometimes, "not Pregnant" rule gets executed first and it turns out later that the person is pregnant i.e, "Pregnant" gets true later on. But the outcome for "not Pregnant" has already run.

So, any suggestion on how to overcome this?

1
As far as I know, the order in which the rules are tested should not matter. When a fact is inserted (or removed or changed) that is relevant to some other rules, those rules are tested again. - tobias_k

1 Answers

1
votes

There is no guarantee of the order in which rules are evaluated when they all match. However, in the example above, the order is being forced in the best way.

The first rule will activate when there is a Person fact in working memory with the appropriate properties.

The second rule will not activate until there is a Person in working memory and a fact called CouldHaveBeenPregnant, which references the person. CouldHaveBeenPregnant is only in working memory when rule 1 has activated and inserted it.

Likewise, the third rule will only activate when there is a Person with matching properties and a HasBeenPregnant fact referencing that person. The HasBeenPregnant fact is only inserted by the second rule.

i.e. Rule 3 cannot activate until after rule 2, which cannot activate until after rule 1.

This is what is known as "inference", and is an important tool for good rule design. Mark Proctor (Drools lead) wrote a good blog entry about it here:

http://blog.athico.com/2009/11/what-is-inference-and-how-does-it.html