Reputation: 317
Completely new to Prolog (SWI-Prolog in this case) so apologies for this very basic question. I have a simple program below.
loves(vincent,mia).
loves(marsellus,mia).
loves(pumpkin,honey_bunny).
loves(honey_bunny,pumpkin).
jealous(X, Y):- loves(X,Z), loves(Y,Z).
I'm a little confused as to the results of the following query:
?- jealous(vincent, X).
X = vincent ;
X = marsellus.
Perhaps I'm just not accustomed to the unification process of Prolog, but shouldn't the answer just be marsellus? Why is vincent included here as a valid result?
Also, as a followup question: Am I correct in that in order to get a result of all the 'jealous' people, I would write a query such as jealous(X, Y). ?
If so, can someone explain the following result of said query?
?- jealous(X, Y).
X = Y, Y = vincent ;
X = vincent,
Y = marsellus ;
X = marsellus,
Y = vincent ;
X = Y, Y = marsellus ;
X = Y, Y = pumpkin ;
X = Y, Y = honey_bunny.
Any help would be greatly appreciated. Thanks!
Upvotes: 2
Views: 850
Reputation: 881293
For your first question, I can see how the output makes sense.
You're asking for a list of people that love the same person that Vincent loves.
Since both Vincent and Marsellus love Mia, the list is {Vincent, Marsellus}
, as you are getting.
I'm not sure of the syntax for Prolog but you'd want something like:
jealous(X, Y):- loves(X,Z), loves(Y,Z), X \== Y.
to remove those cases where X and Y refer to the same person, using whatever symbol in Prolog meaning "not equal to" if it's not \==
.
It's a little hard to be jealous of yourself unless you're suffering from some sort of split-personality disorder and, if you are, you could argue it's not yourself you're actually jealous of, self
becoming a rather fluid concept in those circumstances.
The second question output also makes sense, after a bit of thought, and is related to the same problem as described above. Looking at the output slightly reformatted:
X = Y, Y = vincent ;
X = vincent, Y = marsellus ;
X = marsellus, Y = vincent ;
X = Y, Y = marsellus ;
X = Y, Y = pumpkin ;
X = Y, Y = honey_bunny.
These are the jealousy ouputs, with the X = Y
meaning exactly that, X
and Y
are the same, with Y
being specified as the second item on each line. It can be rewritten as:
X = vincent, Y = vincent ;
X = vincent, Y = marsellus ;
X = marsellus, Y = vincent ;
X = marsellus, Y = marsellus ;
X = pumpkin, Y = pumpkin ;
X = honey_bunny, Y = honey_bunny.
In other words, similar to the first question, everyone is jealous of themselves, as well as any other people who may love a given target.
I suspect that, if you modify the jealousy detector as suggested, all that self-loathing may just disappear, and the world will be a happier place.
Well, other than for Vincent and Marsellus, who obviously still dislike each other, and who are both suffering from unrequited love. The world can sometimes be such a harsh place :-)
Upvotes: 4