Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Prolog predicate with incrementing component

I have a knowledge base consisting of a set of rules whose head of each rule performs assert or retract of complex terms when certain conditions occur.

How can I ensure that Id is incremented with each assert(term(Id,A,B,C))?

like image 823
user3062889 Avatar asked Jul 27 '26 07:07

user3062889


1 Answers

Assuming you don't care about holes in the Id (which occur when retracting id_person/2 clauses) you could do:

:- dynamic nextID/1.
:- dynamic id_person/2.
nextID(0).

assertz_person(P) :-
   nextID(I),
   retract(nextID(I)),
   I1 is I+1,
   assertz(nextID(I1)),
   assertz(id_person(I,P)).

Sample use (works with SWI-Prolog 8.0.0 and SICStus Prolog 4.5.0):

?- id_person(I,P).
false.

?- assertz_person(joan), id_person(I,P).
I = 0, P = joan.

?- assertz_person(al), assertz_person(ian), id_person(I,P).
   I = 0, P = joan
;  I = 1, P = al
;  I = 2, P = ian.
like image 90
repeat Avatar answered Jul 30 '26 08:07

repeat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!