CLIPS规则以降序打印邮件

时间:2013-04-21 05:30:59

标签: clips

我需要一些CLIPS问题的帮助。这就是问题所在:

“假设CLIPS数据库包含以下模板实例化的事实:

(deftemplate recommendation
     (slot name)
     (slot message)
     (slot rating)
)

编写CLIPS规则,根据评级以降序打印消息。每条消息都将与其相关的名称和评级一起打印。“

当存在如下列表时,我知道排序规则:

(deffacts testlist
        (list 1 4 2 3 5 8 7 6 9 0)
    ) 

(defrule sort

         ?f <- (list $?head ?a ?b&:(< ?b ?a) $?tail)
=>
    (retract ?f)

    (assert (list $?head ?b ?a $?tail))
)

但我不确定它何时采用deftemplate格式。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

CLIPS do-for-all-facts可以让您更轻松地执行此类操作,但遗憾的是,默认情况下它并不适用于许多系统,并且需要重新编译CLIPS才能使其可用。

如果您声明所有需要打印的项目的事实,那么您可以使用forall来确定评分最高的项目:

(defrule assert-unprinted "Asserts each item that needs to be printed."
  (print-sorted)
  (recommendation (name ?n))
  =>
  (assert (unprinted ?n)))

(defrule retract-print-sorted "Retract print-sorted after all items enumerated."
  (declare (salience -10))
  ?f <- (print-sorted)
  =>
  (retract ?f))

(defrule print-greatest "Prints the unprinted item with the greatest rating."
  (not (print-sorted))
  ?u <- (unprinted ?name)
  (recommendation (name ?name) (rating ?rating))
  (forall (and (unprinted ?n) (recommendation (name ?n) (rating ?r)))
          (test (<= ?r ?rating)))
  =>
  (retract ?u)
  (printout t ?name " has rating " ?rating "." crlf))

以下是一些示例事实:

(deffacts recommendations
  (recommendation (name chocolate) (rating 10.0))
  (recommendation (name vanilla) (rating 6.8))
  (recommendation (name strawberry) (rating 8.5)))

它们按照这样的降序打印:

CLIPS> (reset)
CLIPS> (assert (print-sorted))
<Fact-4>
CLIPS> (run)
chocolate has rating 10.0.
strawberry has rating 8.5.
vanilla has rating 6.8.
CLIPS> 

答案 1 :(得分:0)

CLIPS> 
(deftemplate recommendation
   (slot name)
   (slot message)
   (slot rating))
CLIPS>      
(deffacts recommendations
   (recommendation (name chocolate) (rating 10.0))
   (recommendation (name vanilla) (rating 6.8))
   (recommendation (name strawberry) (rating 8.5)))
CLIPS> 
(deffunction rating-sort (?f1 ?f2)
   (< (fact-slot-value ?f1 rating) (fact-slot-value ?f2 rating)))
CLIPS>    
(defrule print
   =>
   (bind ?facts (find-all-facts ((?f recommendation)) TRUE))
   (bind ?facts (sort rating-sort ?facts))
   (progn$ (?f ?facts)
      (printout t (fact-slot-value ?f name) " has rating " (fact-slot-value ?f rating) "." crlf)))
CLIPS> (reset)
CLIPS> (run)
chocolate has rating 10.0.
strawberry has rating 8.5.
vanilla has rating 6.8.
CLIPS>