droolsilogjrules

Equivalent Drools syntax for setting a variable from an object within a collection in ILOG


In our ILOG rules irl files we have numerous occurrences of setting a variable from a collection and setting another variable from the collection which doesn't equal the first object

student1: com.company.bom.Student() in all_students;
student2: com.company.bom.Student(!(?this.equals(student2))) in all_students;

In ILOG do these lines just return the first and second object in the collection?

Would be the following be the best way to do the same in Drools within a drl rule file?

student1: com.company.bom.Student() from all_students.get(0);
student2: com.company.bom.Student() from all_students.get(1);

Solution

  • You should be able to check what your ILOG do, so I'm just answering the Drools part.

    In Drools, obtaining an object from some Collection in reach can be done using from <expression>. Thus, you can indeed write

    University( $roster: roster )
    $student1: Student() from $roster.get(0)
    $student2: Student() from $roster.get(1)
    

    This rule fires once with the first two students in the roster collection, but it is bound to raise an exception if there are less than two students.

    University( $roster: roster )
    $student1: Student() from $roster
    $student2: Student( this != $student1 ) from $roster
    

    This rule fires for each ordered pair of different students, with one particular pair causing two rule firings.