Your problem is that Z
it's not bound when your rule calls for \+likes(X,Z)
, then at least there will always be Z=Y that invalidates loves/2. I mean, since likes(X,Y) is true, surely will be true likes(X,Z).
Change it this way:
loves(X,Y):- likes(X,Y), \+ (( likes(X,Z), Z \= Y )).
and you'll get
?- loves(X,Y).
X = john,
Y = mary.