【问题标题】:How can I define a global variable in a defrule and use it in another defrule in CLIPS?如何在一个 defrule 中定义一个全局变量并在 CLIPS 的另一个 defrule 中使用它?
【发布时间】:2018-06-02 06:06:00
【问题描述】:

我在 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))

【问题讨论】:

    标签: global-variables clips


    【解决方案1】:

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

    您也可以使用 CLIPS 的 build 表达式:

             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)
    

    【讨论】:

    • 我建议,你打开另一个问题,因为它在概念上与你原来的问题无关。
    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 2017-03-04
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    相关资源
    最近更新 更多