Search code examples
prolog

False value returned in Prolog?


sitting(mary, james).
sitting(rosie, andrew).
sitting(kiera, tom).

issitting(X, Y) :- sitting(X, Y).

Hey guys, I basically want to check who the true or false values of who is sitting next to who,

When I type in the compiler

issitting(rosie, andrew). 

A true value is returned, however, when I type

issitting(andrew, rosie). 

A false value is returned (Which should be true because they are sitting next to each other). I don't want to add three extra lines of code should the user check for who is sitting next to each other (with all possible combinations).

How would you alter the rule to get Prolog to understand that if the user switches the names around, they're still true (NOT false).

I don't understand why it's giving me 'false' .

I'm stuck and this is the best I could get done so far :/

Thank you.


Solution

  • (I could just point out the problem, but then you would not learn anything. I assume you are using SWI, since you say that false is returned.)

    ?- issitting(andrew, rosie).
       false.
    

    Let me restate what your problem is: You are expecting that issitting(andrew, rosie) is true. But it is not. What would you do if you asked that question to a person? Probably you would ask why? Why isn't andrew sitting next to rosie? And, say, you did not understand the explanations, you might have asked another question:

    Is andrew at least sitting next to anyone?

    So this question is a generalization of the original question. In Prolog, we can do the very same thing with the help of variables like so:

    ?- issitting(andrew, Anyone).
       false.
    

    So now we know that andrew issitting next to nobody? Confused? Well, we can generalize the query once again:

    Is there at least one person sitting next to anyone?

    ?- issitting(Person, Anyone).
       Person = mary, Anyone = james
    ;  Person = rosie, Anyone = andrew
    ;  Person = kiera, Anyone = tom.
    

    So there are some persons around. Effectively, the reason is that you have sitting/2 and another relation issitting/2. You need to generalize issitting/2 by adding the following rule:

    issitting(X, Y) :- sitting(Y, X).
    

    But the point was to show you a good general debugging strategy:

    In case of unexpected failure, try to generalize your query (and your program).