Search code examples
drools

How to obtain the minimum of an updated value in Drools?


I want to use Drools to manage some questions in a form. Depending of the answer of the question, the question score be updated with a value. Then I want to obtain the minimum value of all questions answered in a category.

One example:

Category "Replicant or not?":
You’re in a desert walking along in the sand when all of the sudden you look down, and you see a tortoise, crawling toward you. You reach down, you flip the tortoise over on its back. Why is that? 
1. it was an error. (5 points).
2. It is the funniest think to do at a dessert. (3 points).
3. You want to kill the tortoise in the most painful way (1 point). 
//More other questions.

At the end of the test, the minimum value for each category will be the used one.

Then I have defined some drools rules to define the score for each one (in a spreadsheet, by I put the rule translations):

rule "Question_1"
    when
            $qs: Questions(checked == false);
            $q: Question(category == 'cat1', question == "q1", answer == "a") from $qs.getQuestions();
    then
            $q.setValue(5);
            $qs.setChecked(true);
            update($qs);
end

checked value is used to avoid to reuse the rule when updating. category, question, answer are used for classifying the question.

And then, my rule for calculate the minimum is:

rule "Min value"
when
    $qs: Questions(checked == true);
    not q:Question($v: value; value < $v) from $qs.getQuestions();
then
    $qs.setMinValue($v);
    System.out.println("The smallest value is: "+ $v);
end

The error obtained is:

$v cannot be resolved to a variable

Then, the question is: How can I obtain the minimum value of a value setted by a previous rule?


Solution

  • The duplication of "from " can be avoided, using the accumulate CE which is about 25% faster.

    rule "getmin"
    when
        Questions( $qs: questions )
        accumulate( Question( $v: value ) from $qs; $min: min( $v ) )
    then
        System.out.println( "minimum is " + $min );
    end