Search code examples
recursionprologlogic-programming

Prolog Recursion might not be exiting with proper boundary condition


Given the following database:

location(desk, office).
location(apple, kitchen).
location(flashlight, desk).
location('washing machine', cellar).
location(nani, 'washing machine').
location(broccoli, kitchen).
location(crackers, kitchen).
location(computer, office).
location(envelope, desk).
location(stamp, envelope).
location(key, envelope).

is_contained_in(X, Y) :-
    location(Z, Y),
    is_contained_in(X, Z).

I expect the following query

is_contained_in(Y, kitchen).

to yield all the items are inside the kitchen. Instead, all the output I get is false. Furthermore, I expect my query to yield me a list of all the items that exist inside the kitchen regardless of whether or not they are inside other items.

Why is the the is_contained_in predicate not giving me the desired result with the query

is_contained_in(Y, kitchen).

Solution

  • The problem is that is_contained_in(X, Y) does not have a condition to match when X is directly located in Y, and because any containment relation will eventually require direct location to match, it won't find anything. You need an extra clause to handle that case:

    is_contained_in(X, Y) :- location(X, Y).