javadroolsrule-engineexpert-systemjess

Return a value from rule jess or drools (expert system)


In jess the way to return a string from a rule is like that :

(defrule welcome-toddlers
"Give a special greeting to young children"
(person {age < 3})
=>
(printout t "Hello, little one!" crlf))

My question is how implement the return function, this is what I want:

(defrule welcome-toddlers
"Give a special greeting to young children"
(person {age < 3})
=>
(return "Hello, little one!"))

if not possible how do that in drools ??


Solution

  • A rule isn't called like a function - so your question doesn't make sense. Rules fire, due to what happens in Working Memory, in some (apparently) random order - so where should that string from one of those rules go? The (run) function (fireAllRulesmethod) just returns the number of rules that were fired, and that's that.

    Where would you want to have that string resulting from welcome-toddlers? A way of passing data that's being created in a rule to that point in your application has to be selected. Here's some popular options:

    1. Declare and set a global that's capable of storing all the results from your rules. Could be a List or a Map - take your pick.
    2. Insert the result as a fact in Working Memory. Perhaps you need to define some simple template for holding the value and an identification. You can fetch those facts from some Java app code, using the API.
    3. Store the value into the very fact that is responsible for triggering the rule, e.g., add a slot greeting to person and store it there. (Take care not to cause an endless loop.)
    4. It is also possible to design some static method in a Java class that takes care of the value and stores it appropriately. You can call that from the consequence ("when" part).

    Apart from some differences in terminology, it's just the same thing in Drools.

    Both systems have documentation where you can find all the details to this and other issues.