這個問題並不適合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.");
}
正如我所說的,這ISN非常適合,因爲結果代碼比原來的代碼更大更復雜。在使用規則引擎的情況下,如果你有多個交互規則,這樣的Jess程序沒有比這更多的開銷,所以相當快地開始看起來像是等同於Java代碼的簡化。祝Jess好運!
當人們回答你的問題時,你需要投票和/或接受答案,否則他們會停止回答你的問題...... –