ANA
ANA

Reputation: 83

CLIPS Beginner: How to add an automatic counter attribute in facts using Python and Clipspy

I want to add an automatic counter as an attribute in fact using clipspy it means The first fact, that you assert counts as number 1, the second as number 2 and so on. As I am beginner to Clips rules and facts coding I am not getting any idea how to add this. Thank you in advance if anyone can help me resolve this problem. Following is my code:

import clips

template_string = """
(deftemplate person
  (slot name (type STRING))
  (slot surname (type STRING)))
"""
Dict = {'name': 'John', 'surname': 'Doe' }

env = clips.Environment()
env.build(template_string)

template = env.find_template('person')
fact = template.assert_fact(**Dict)
assert_fact = fact

env.run()

for fact in env.facts():
    print(fact)

Upvotes: 0

Views: 175

Answers (1)

noxdafox
noxdafox

Reputation: 15060

Fact objects already have indexes which indicate their assertion position.

Indexes start from 1.

print(fact.index)

If you want to add an incremental counter to the fact itself, you can do it using a defglobal, a deffunction and the default-dynamic property of a slot.

(defglobal ?*counter* = 0)

(deffunction increase () 
  (bind ?*counter* (+ ?*counter* 1)))

(deftemplate person  
  (slot name (type STRING))  
  (slot surname (type STRING)) 
  (slot counter (type INTEGER) (default-dynamic (increase))))   

(assert (person (name "John") (surname "Doe")))

Upvotes: 1

Related Questions