我怎样才能在一个定义中定义一个全局变量,并在CLIPS的另一个定义中使用它呢?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (40)

我在CLIPS中编写了这些代码,但它不起作用。它说“局部变量不能被deffact访问”。我也想在其他规则中使用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))
提问于
用户回答回答于

错误消息确切地说明了问题所在。问题是,deffacts只会在(重置)之后声明。因此,在(重置)所有事实被移除并且断言被断言之后。因此,在评估deffacts语句的那一刻,没有局部变量仍然存在(另外:局部变量仅在它们定义的范围中可见:deffunction,defrule)。全局变量也不起作用,因为在你调用(重置)的那一刻,它们将被放回。

你也可以使用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)

扫码关注云+社区

领取腾讯云代金券