1

I am a begginer at jess rules so i can't understand how i could use it. I had read a lot of tutorials but i am confused.

So i have this code :

Date choosendate = "2013-05-05";
Date date1 = "2013-05-10";
Date date2 = "2013-05-25";
Date date3 = "2013-05-05";
int var = 0;

    if (choosendate.compareTo(date1)==0)
                {
                    var = 1;
                }
                else if (choosendate.compareTo(date2)==0)
                {
                    var = 2;
                }
                else if (choosendate.compareTo(date3)==0)
                {
                    var = 3;
                }

How i could do it with jess rules? I would like to make a jess rules who takes the dates , compare them and give me back in java the variable var. Could you make me a simple example to understand it?

4

1 回答 1

1

这个问题不适合 Jess 所写的(Java 代码短而高效),但我可以向您展示一个可以适应其他更复杂情况的解决方案。首先,您需要定义一个模板来保存Date,int对:

(deftemplate pair (slot date) (slot score))

然后,您可以使用模板创建一些事实。这些在某种程度上等同于您的date1,date2等,除了它们将每个日期与相应的var值相关联:

(import java.util.Date)
(assert (pair (date (new Date 113 4 10)) (score 1)))
(assert (pair (date (new Date 113 4 25)) (score 2)))
(assert (pair (date (new Date 113 4 5))  (score 3)))

我们可以定义一个全局变量来保存最终的计算分数(使其更容易从 Java 中获取。)这等效于您的var变量:

(defglobal ?*var* = 0)

假设“选择的日期”将在一个有序的事实chosendate中,我们可以编写如下规则。它会替换您的语句链,if并将您选择的日期与工作内存中的所有日期进行比较,直到找到匹配项,然后停止:

(defrule score-date
    (chosendate ?d)
    (pair (date ?d) (score ?s))
    =>
    (bind ?*var* ?s)
    (halt))

好的,现在,上面的所有代码都放在一个名为dates.clp. 以下 Java 代码将使用它(Rete.watchAll()包含对 的调用,因此您可以看到一些有趣的跟踪输出;您可以将其留在实际程序中):

    import jess.*;
    // ...

    // Get Jess ready
    Rete engine = new Rete();
    engine.batch("dates.clp");
    engine.watchAll();

    // Plug in the "chosen date"
    Date chosenDate = new Date(113, 4, 5);
    Fact fact = new Fact("chosendate", engine);
    fact.setSlotValue("__data", new Value(new ValueVector().add(chosenDate), RU.LIST));
    engine.assertFact(fact);

    // Run the rule and report the result
    int count = engine.run();
    if (count > 0) {
        int score = engine.getGlobalContext().getVariable("*var*").intValue(null);
        System.out.println("Score = " + score);
    } else {
        System.out.println("No matching date found.");
    }

正如我所说,这不是一个很好的选择,因为生成的代码比原始代码更大更复杂。如果您有多个交互的规则,那么使用规则引擎是有意义的;这样的 Jess 程序没有比这更多的开销,因此与等效的 Java 代码相比,很快就开始看起来像简化了。祝杰斯好运!

于 2013-07-24T12:22:45.553 回答