How to check for existence of a facts CLIPS without seeing an error?

40 Views Asked by At

My code might have facts such as: (assert (person "Jack")) (assert (fruit "apple")) I would like to print for example the person if only it exists such as The person is "Jack"

I tried using this condition (if (find-fact ((?f person)) TRUE) then (printout t "The fact exists." crlf) ) but if the person relation does not exist, it shows an error. I do not want to see anything or error if the fact does not exist. Is this possible Thank you.

1

There are 1 best solutions below

2
noxdafox On

Assuming the error you get is the following:

[PRNTUTIL1] Unable to find deftemplate 'person'.

The reason is you are using an ordered fact. Ordered facts do not have associated deftemplates, hence the error. CLIPS creates an implicit deftemplate whenever a new fact of a give type is created. This is why you see the find-fact function working if the person fact is asserted.

In [1]: (get-deftemplate-list)
()
In [2]: (assert (person "Jack"))
(person "Jack")
In [3]: (get-deftemplate-list)
('person',)

The best solution, would be to use deftemplate facts instead of ordered ones. In this way, the engine knows beforehand which types of fact exist and can use this information to build its internal queries.

In [1]: (deftemplate person
   ...:   (slot name))

In [2]: (get-deftemplate-list)
('person',)
In [3]: (find-fact ((?f person)) TRUE)
()
In [4]: (assert (person (name "Jack")))
(person (name "Jack"))
In [5]: (find-fact ((?f person)) TRUE)
(TemplateFact: (person (name "Jack")),)