如何在一个defrule中定义一个全局变量并在CLIPS的另一个defrule中使用它?

时间:2018-06-01 18:08:24

标签: global-variables clips

我在CLIPS中编写了这些代码,但它不起作用。它说"本地变量不能被deffact访问。"我还想在其他defrules中使用number1和number2的值。如何在规则中将这些变量定义为全局?

(deffunction calculation1
(?x ?y)
(+ ?x ?y))
(defrule rule1
=>
(printout t "What is the first number?")
(bind ?number1 (read))
(assert (number-1 ?number1))
(printout t "What is the second number?")
(bind ?number2 (read))
(assert (number-2 ?number2))
(bind ?theirsum (calculation1 ?number1 ?number2))
(printout t "The sum is " ?theirsum crlf))
(deffacts data
(first num1 ?number1
second num2 ?number2))

1 个答案:

答案 0 :(得分:1)

错误消息确切地说明了问题所在。 我只能猜测,你想要完成什么。问题是,仅在(重置)之后断言deffacts。因此,在(重置)之后,所有事实都被删除并且deffacts被断言。因此,在评估deffacts语句的那一刻,仍然不存在局部变量(另外:局部变量仅在它们定义的范围内可见:deffunction,defrule)。全局变量也不起作用,因为它们会在您调用(重置)的那一刻被撤回。 我想到的一个解决方案是黑客攻击:见Clips hack

您还可以使用CLIPS'构建表达式:

         CLIPS (6.30 3/17/15)
CLIPS> (defrule rule1
=>
    (printout t "What is the first number?")
    (bind ?number1 (read))
    (assert (number-1 ?number1))
    (printout t "What is the second number?")
    (bind ?number2 (read))
    (assert (number-2 ?number2))
    (bind ?theirsum (+ ?number1 ?number2))
    (printout t "The sum is " ?theirsum crlf)
    (build (str-cat
        "(deffacts data (first num1 " ?number1 " second num2 " ?number2     "))"
        )
    )
)
CLIPS> (run)
What is the first number?1
What is the second number?2
The sum is 3
CLIPS> (get-deffacts-list)
(initial-fact data)
CLIPS> (reset)
CLIPS> (facts)
f-0     (initial-fact)
f-1     (first num1 1 second num2 2)
For a total of 2 facts.

或者您可以使用文件:

         CLIPS (6.30 3/17/15)

CLIPS> (defrule rule1   
=>
    (printout t "What is the first number?")
    (bind ?number1 (read))
    (assert (number-1 ?number1))
    (printout t "What is the second number?")
    (bind ?number2 (read))
    (assert (number-2 ?number2))
    (bind ?theirsum (+ ?number1 ?number2))
    (printout t "The sum is " ?theirsum crlf)
    (printout data
        "(deffacts data (first num1 " ?number1 " second num2 " ?number2 "))"
    crlf)
    (close data)    
)
CLIPS> (run)
What is the first number?1
What is the second number?2
The sum is 3
CLIPS> (load data.dat)
Defining deffacts: data
TRUE
CLIPS> (get-deffacts-list)
(initial-fact data)