I'm trying to replace Jess with Drools as backward chaining rule engine in our project. I was looking for simple examples about how backward chaining is done with Drools. Interestingly, there's only 1 same example on every site (which I don't get how it's BC but let's forget it for now).
Very trivial example of BC in Jess:
//q is a fact template with a slot named 'n'
//when there's a q with n==8 print something
//I need a q with n==8 to fire a rule so I will insert it myself!
(deftemplate q (slot n))
(do-backward-chaining q)
(defrule printq (q (n 8)) => (printout t "n is eight! yeah!" crlf))
(defrule iNeedn8 (need-q (n 8)) => (assert (q (n 8))))
(reset)
(run 1)
//fires printq and prints to console...
Equivalent in Drools:
package com.example;
declare Q
n : int
end
rule "print q"
when
Q(n == 8)
then
System.out.println("n is eight by drools!");
end
//I'M LOST HERE! HELP!
How can I achieve same behaviour with Drools?
In Drools, the general idea of BC is to use queries. In addition to your rule "print q" you need:
There is no way to instruct Drools to detect the missing fact all by itself; you have to provide the goal and queries to "bridge the gap".