Swi prologue denial

It was hard for me to find clear answers to the denial in Prolog, so I apologize if this is an obvious question:

I am trying to write simple code that logically says that "X and Y love each other if X likes Y and only Y". My .pl code looks something like this:

likes(mary,john). likes(mary,chad). likes(john,mary). loves(X,Y):- likes(X,Y), \+likes(X,Z). 

Then I run my program and just ask:

 ?- loves(X,Y). 

but he always fails. By my logic, he should return, saying: "X = john, Y = mary."

I tried several combinations of separating negation into cuts, trying to use multiple lines to define β€œlikes” ... I probably don’t have the main principle of negation, or maybe there’s an even simpler way to realize what I'm trying to do. Please let me know if you can help!

I use SWI-Prolog (swipl) from Debian Software Manager, if that helps at all, although I doubt it will make a big difference.

+6
source share
1 answer

Your problem is that Z is not bound when your rule calls \+likes(X,Z) , then at least there will always be Z = Y, which invalidates love / 2. I mean, since the sympathies (X, Y) are true, they will surely be true sympathies (X, Z).

Change it like this:

 loves(X,Y):- likes(X,Y), \+ (( likes(X,Z), Z \= Y )). 

and you will get

 ?- loves(X,Y). X = john, Y = mary. 
+5
source

All Articles