0

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)
noxdafox
  • 14,439
  • 4
  • 33
  • 45
ANA
  • 83
  • 5

1 Answers1

1

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")))
noxdafox
  • 14,439
  • 4
  • 33
  • 45
  • This shows the index number separately but I want to make an attribute which automatically increases when a fact is added like in c++ there is i++. For example: template_string = """ (deftemplate person ( slot counter ()) (slot name (type STRING)) (slot surname (type STRING))) """ And the counter increases every time a fact is added like a row number I guess – ANA Sep 27 '21 at 14:24
  • I understand the concept but I cannot find the correct syntax. – ANA Sep 27 '21 at 17:25
  • The sample is written in CLIPS language. You can either install the interpreter or the Jupyter console iCLIPS to verify it. The above constructs can be added to the environment via the `build` function. – noxdafox Sep 27 '21 at 20:11
  • It is not increasing the counter but only adding (counter 1) in front of every fact person – ANA Oct 12 '21 at 13:42
  • The code above works correctly. Make sure the syntax is correct when it comes to assigning and modifying global variables. You can refer to the [Basic Programming Guide](http://clipsrules.sourceforge.net/documentation/v640/bpg.pdf) to see how to achieve the above. – noxdafox Oct 12 '21 at 13:51