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



给定以下数据库:

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

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

为什么is_contained_in谓词没有通过查询给我所需的结果

is_contained_in(Y, kitchen).

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

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

最新更新