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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With