pythonclipsclipspy

how to retract a fact using clipspy


How to retract a fact in CLIPS from a python fucntion using clipspy. I tried using build() but the fact is still there.

;;--KB.clp--;;
(defrule main-intent

        (initial-fact)
        =>
        (assert (fact one))
        (assert (fact two))
)

(defrule rule_1
        ?p <- (fact one)
        ?q <- (fact two)
        =>
        (py_pfact)
        (py_retract ?p ?q)
        (py_pfact)
)

Run from python

# run.py
import clips

clips_env = clips.Environment()

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

def py_retract(p, q):
    clips_env.build('retract '+str(p))

clips_env.define_function(py_retract)
clips_env.define_function(py_pfact)

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

The output is:

(initial-fact)
(fact one)
(fact two)
(initial-fact)
(fact one)
(fact two)

(fact one) not retracted. It seems ?p is not containing the fact identifier but the whole fact itself. In the past I have used PyCLIPS in this way and it worked. Is it possible to retracts a fact using ClipsPy?


Solution

  • In clipspy the environment.build method is analogous to CLIPS C API EnvBuild and it allows to build constructs such as deftemplates and rules as strings within the engine.

    clips_env.build("(deftemplate foo (slot bar) (slot baz))")
    

    If you want to retract a fact, you can simply call its method.

    def py_retract(p, q):
        p.retract()