Dragos Polifronie
Dragos Polifronie

Reputation: 159

How to negate in prolog?

I can't understand how the negation works in Prolog. I followed some questions on the same topic but I still can't figure it out, so, sorry if this is repetitive Say I have this rules:

female(mary).
female(sandra).
female(juliet).
female(lisa).
male(peter).
male(paul).
male(dony).
male(bob).
male(harry).
parent(bob, lisa).
parent(bob, paul).
parent(bob, mary).
parent(juliet, lisa).
parent(juliet, paul).
parent(juliet, mary).
parent(peter, harry).
parent(lisa, harry).
parent(mary, dony).
parent(mary, sandra).

What I'm trying to achieve is getting the combinations of all non-parent relationship: I tried like this:

not_parent(X, Y) :- \+parent(X, Y).

this works for not_parent(bob, juliet) but for not_parent(X, Y) just shows false. I saw this example and tried this too:

father_of(X, Y):-male(X), parent(X, Y). 
mother_of(X, Y):-female(X), parent(X, Y).


not_parent(X, Y):- 
    male(X), \+ father_of(X, Y);
    female(X), \+ mother_of(X, Y).

but this doesn't quite work, as it only shows names for X and not X, Y as I intended to.

Upvotes: 2

Views: 127

Answers (1)

CapelliC
CapelliC

Reputation: 60014

Negation as failure is known as weak negation, and works as expected only under the closed world assumption. This means in practical terms that you must supply 'enough instantiated' goals to the (\+)/1 operator. I would try - for simplicity - to introduce a genderless predicate, like person/1, and then I would ask for:

person(P) :- female(P) ; male(P).
not_parent(X,Y) :- person(X),person(Y),X@<Y,\+parent(X,Y).

Upvotes: 1

Related Questions