Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog: How do I check whether item exists in the database before adding?

Tags:

prolog

I start out with a blank database. I need to add some database entries to it, for example:

person(John,male)
person(Veronica,female)
person(Jessica,female)

I am adding entries like this:

add_person(N,G):-asserta(person(N,G)).

Howerver, I do not want to add the same person twice, so I need to check before adding.

I am trying to do it this way:

add_person(N,G):- \+ person(N,G),asserta(person(N,G)).

The problem is that I cannot query the database with, say person(John,male) if my database is blank. So person(N,G) fails with existence error, and I cannot add at all.

Any thoughts?

like image 344
Serpent Avatar asked Dec 19 '25 14:12

Serpent


2 Answers

I'm not sure which variant of Prolog you're using, but you can declare some predicates to be dynamic, by putting this line at the top of your code:

:- dynamic person/2.

This is described in the SWI-Prolog documentation.

like image 165
Raceimaztion Avatar answered Dec 21 '25 11:12

Raceimaztion


The way you write John is a variable and not an atom. You should use only lowercase for atoms (john, veronica, etc.). I just tried your code and it works fine:

person(john, male).

add_person(N,G):-
    \+ person(N,G),
    asserta(person(N,G)).

Adding john again fails and returns false.

like image 22
sakisk Avatar answered Dec 21 '25 10:12

sakisk



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!