0
votes

I have following facts

declare PriceInfo
    price : Integer
end

I am using this rule to insert:

rule "insert" agenda-group "find-rotated-house" when

then
    PriceInfo p1 = new PriceInfo();
    PriceInfo p2 = new PriceInfo();
    PriceInfo p3 = new PriceInfo();
    PriceInfo p4 = new PriceInfo();
    PriceInfo p5 = new PriceInfo();

    p1.setPrice(200);
    p2.setPrice(300);
    p3.setPrice(400);
    p4.setPrice(500);
    p5.setPrice(600);

    insert(p1);
    insert(p2);
    insert(p3);
    insert(p4);
    insert(p5);
end

This will insert 5 facts of PriceInfo in to rule engine. I am trying to sort it in ascending or descending order from this rule.

rule "sort-number"
    agenda-group "find-rotated-house"
    when
        $priceInfo : PriceInfo( $price : price)
        not PriceInfo(price < $price)
    then
        $logger.info($priceInfo.toString());
        retract($priceInfo);
end

However, in this rule, I am retracting the fact. If I am not retracting I am getting minimum value i.e. 200. Other facts are not activating. I want to keep the fact intact in RE after sorting.

This rule is also working but with retract.

rule "sort-number-1"
    agenda-group "find-rotated-house"
    when
         Number($intValue : intValue ) from accumulate( PriceInfo( $price : price), min($price) )
         $p : PriceInfo( price == $intValue)
    then
        $logger.info($p.toString());
        retract($p);
end

Please help.

Thanks

1

1 Answers

1
votes

A good answer depends on for what you need the sort order, whether it needs to be maintained over eventual inserts, modifies (prices do change) and deletes, whether it will have to be used repeatedly, etc.

Here is one possibility:

rule "sort price info"
when
    $list: ArrayList() from collect( PriceInfo() )
then
    $list.sort( ... ); // use suitable Comparator
end

Now you have a sorted list of PriceInfo objects.

You could wrap this list into an object and insert it as a fact. This might let you write rules such as

rule "10 cheap ones"
when
    $p: PriceInfo()
    PriceList( $l: list )
    eval( $l.indexOf($p) < 10 )
then ... end