繁体   English   中英

CLIPS:强制规则重新评估全局变量的值?

[英]CLIPS: forcing a rule to re-evaluate the value of a global variable?

是否有可能导致CLIPS在去毛刺中重新评估全局变量的值? 我有这个:

(defrule encourage "Do we have a GPA higher than 3.7?"
    (test (> (gpa) 3.7))
    =>
    (printout t "Keep up the excellent work!" crlf))

gpa是根据两个全局变量(成绩和学分数)计算并返回数字的函数。 我读到某个地方,对全局变量的更改不会调用模式匹配。 我该如何强迫呢? 只要GPA高于3.7,我就想每次运行都打印该字符串。

请勿尝试以这种方式使用全局变量或函数调用。 首先,全局变量专门设计为不触发模式匹配。 其次,对于CLIPS来说,知道何时需要重新评估函数调用会有些不可思议,因为有许多更改可能导致函数返回不同的值,而不仅仅是对全局变量的更改。 如果您希望特定信息触发模式匹配,则将其粘贴在事实或实例中。 如果您对函数调用进行参数化并绑定要在规则条件下用作参数的值,它将使您的代码更易于理解。

CLIPS> (clear)
CLIPS> 
(deffunction gpa (?grade-points ?number-of-credits)
   (/ ?grade-points ?number-of-credits))
CLIPS>    
(defrule encourage "Do we have a GPA higher than 3.7?"
    (grade-points ?gp)
    (number-of-credits ?noc)
    (test (> (gpa ?gp ?noc) 3.7))
    =>
    (printout t "Keep up the excellent work!" crlf))
CLIPS> (assert (grade-points 35) (number-of-credits 10))
<Fact-2>
CLIPS> (agenda)
CLIPS> (facts)
f-0     (initial-fact)
f-1     (grade-points 35)
f-2     (number-of-credits 10)
For a total of 3 facts.
CLIPS> (retract 1)
CLIPS> (assert (grade-points 38))
<Fact-3>
CLIPS> (agenda)
0      encourage: f-3,f-2
For a total of 1 activation.
CLIPS>

或者,您可以使用事实查询功能遍历一组事实,以根据事实而不是全局变量动态计算gpa。 每次您修改这些事实之一(添加或删除)时,您也可以声明一个事实,指示需要重新检查gpa以触发鼓励规则。

CLIPS> (clear)
CLIPS> 
(deftemplate grade
   (slot class)
   (slot grade-points)
   (slot credits))
CLIPS> 
(deffunction gpa ()
   (bind ?grade-points 0)
   (bind ?credits 0)
   (do-for-all-facts ((?g grade)) TRUE
      (bind ?grade-points (+ ?grade-points ?g:grade-points))
      (bind ?credits (+ ?credits ?g:credits)))
   (if (= ?credits 0)
      then 0
      else (/ ?grade-points ?credits)))
CLIPS> 
(defrule encourage
   ?f <- (check-gpa)
   =>
   (retract ?f)
   (if (> (gpa) 3.7)
      then
      (printout t "Keep up the excellent work!" crlf)))
CLIPS> (gpa)
0
CLIPS> (assert (check-gpa))
<Fact-1>
CLIPS> (run)
CLIPS>  (assert (grade (class Algebra) (grade-points 12) (credits 3)))
<Fact-2>
CLIPS> (gpa)
4.0
CLIPS> (assert (check-gpa))
<Fact-3>
CLIPS> (run)
Keep up the excellent work!
CLIPS> (assert (grade (class History) (grade-points 6) (credits 2)))
<Fact-4>
CLIPS> (gpa)
3.6
CLIPS> (assert (check-gpa))
<Fact-5>
CLIPS> (run)
CLIPS> (assert (grade (class Science) (grade-points 12) (credits 3)))
<Fact-6>
CLIPS> (gpa)
3.75
CLIPS> (assert (check-gpa))
<Fact-7>
CLIPS> (run)
Keep up the excellent work!
CLIPS>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM