Prolog递归可能不会以适当的边界条件退出

Prolog Recursion might not be exiting with proper boundary condition

给定以下数据库:

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).

我期待以下查询

is_contained_in(Y, kitchen).

yield 所有物品都在厨房里。相反,我得到的所有输出都是 false。此外,我希望我的查询能为我提供厨房内存在的所有物品的列表,无论它们是否在其他物品中。

为什么 is_contained_in 谓词在查询中没有给我想要的结果

is_contained_in(Y, kitchen).

问题是当X直接位于Y时,is_contained_in(X, Y)没有条件匹配,因为任何包含关系最终都需要直接位置匹配,它什么也找不到。您需要一个额外的子句来处理这种情况:

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