Search code examples
prolog

Prolog doesn't return the correct query (to my knowledge) when added the (X \= Y) clause


Knowledge base:

loves(vincent,mia).
loves(marcellus,mia).
loves(pumpkin,honey_bunny).
loves(honey_bunny,pumpkin).


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

Now I type jealous(vincent, X). , it returns false. Shouldn't it be X = marcellus, since marcellus is not equal to vincent but they both love mia? Am I missing something?


Solution

  • When you run jealous(vincent, Y)., it tries to see if vincent is not equal to Y. However, Y is uninstantiated at this point as there has been no possibility to pick from.

    An easy fix is to place the X \= Y. at the end of your predicate like so:

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

    This gives the intended answer: X = marcellus.

    An easy way to see what is going on next time is to run trace.; this lets you debug your code easily. (This is the case for SWI-Prolog, not sure about other versions).