使用ClipsPy以编程方式修改事实栏 [英] Programmatically modify a fact slot using ClipsPy

查看:118
本文介绍了使用ClipsPy以编程方式修改事实栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用ClipsPy在CLIPS中修改模板的事实.

How to modify a fact of a template in CLIPS using ClipsPy.

我尝试了重新分配插槽值并在clips.build例程中发送了修改,(请参见下面的py_modify函数)无效.

I have tried the reassigning slot value and sending modify in clips.build routine, (see py_modify function below) which did not work.

这是.clp文件

;; KB.clp
(deftemplate t
    (slot s_1 (type SYMBOL)))

(defrule main-intent
    (initial-fact)
    =>
    (assert (t (s_1 v_1)))
)

(defrule rule_1
    ?p<-(t (s_1 ?v))
    =>
    (printout t"BEFORE"crlf) (py_pfact)
    (py_modify ?p)
    (printout t"AFTER"crlf) (py_pfact)
)

这是python文件.

This is the python file..

# run.py
import clips

clips_env = clips.Environment()

def py_pfact():
    for fact in clips_env.facts():
        print(fact)

def py_modify(p):
    print("--modifying",p["s_1"])
    p["s_1"] = "v_2"  # Try 1
    clips.build("(modify "+str(p.index)+ " (s_1 v_2)") #Try 2

clips_env.define_function(py_pfact)
clips_env.define_function(py_modify)

clips_env.load("KB.clp")
clips_env.reset()
clips_env.run()

输出是

 BEFORE
(initial-fact)
(t (s_1 v_1))
--modifying v_1
AFTER
(initial-fact)
(t (s_1 v_1))

我希望将s_1插槽从v_1修改为v_2,但事实并非如此.

I expect s_1 slot to be modified to v_2 from v_1, but it is not.

推荐答案

environment.build 方法用于在引擎内构建构造(defruledeftemplate等).要执行CLIPS代码,您需要使用 environment.eval .

The environment.build method is for building constructs (defrule, deftemplate, etc.) within the engine. To execute CLIPS code, you need to use environment.eval.

在CLIPS 6.30中,一旦声明就无法更改事实(6.40为此添加了API).唯一的方法是收回旧的,并用更新的值声明新的.

In CLIPS 6.30 it's not possible to change a fact once asserted (6.40 added APIs for that). Only way to do so is by retracting the old one and asserting a new one with updated values.

def modify_fact(fact):
    """Modify a template fact."""
    fact.retract()

    new_fact = fact.template.new_fact()
    new_fact.update(dict(fact))  # copy over old fact slot values

    new_fact["s_1"] = clips.Symbol("v_2") 

    new_fact.assertit()

CLIPS提供了与modify命令完全相同的命令:撤回事实并使用新值对其进行断言.但是,不能通过environment.eval来使用它,因为事实索引不能通过API来使用.如果要修改规则中的事实,最好直接使用modify命令.

CLIPS provides the modify command which does the exact same: retracts the fact and asserts it with the new value. Nevertheless, it cannot be used via environment.eval as fact indexes cannot be used via the API. If you want to modify a fact within a rule, you'd better use the modify command directly.

(defrule rule_1
  ?p <- (t (s_1 ?v))
  =>
  (modify ?p (s_1 v_2)))

这篇关于使用ClipsPy以编程方式修改事实栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆