我正在尝试自学 Prolog。下面,我编写了一些我认为应该返回无向图中节点之间的所有路径的代码……但事实并非如此。我试图理解为什么这个特定的代码不起作用(我认为这将这个问题与类似的 Prolog 寻路帖子区分开来)。我在 SWI-Prolog 中运行它。有什么线索吗?
% Define a directed graph (nodes may or may not be "room"s; edges are encoded by "leads_to" predicates).
room(kitchen).
room(living_room).
room(den).
room(stairs).
room(hall).
room(bathroom).
room(bedroom1).
room(bedroom2).
room(bedroom3).
room(studio).
leads_to(kitchen, living_room).
leads_to(living_room, stairs).
leads_to(living_room, den).
leads_to(stairs, hall).
leads_to(hall, bedroom1).
leads_to(hall, bedroom2).
leads_to(hall, bedroom3).
leads_to(hall, studio).
leads_to(living_room, outside). % Note "outside" is the only node that is not a "room"
leads_to(kitchen, outside).
% Define the indirection of the graph. This is what we'll work with.
neighbor(A,B) :- leads_to(A, B).
neighbor(A,B) :- leads_to(B, A).
如果 A --> B --> C --> D 是无环路径,则
path(A, D, [B, C])
应该是真的。即,第三个参数包含中间节点。
% Base Rule (R0)
path(X,Y,[]) :- neighbor(X,Y).
% Inductive Rule (R1)
path(X,Y,[Z|P]) :- not(X == Y), neighbor(X,Z), not(member(Z, P)), path(Z,Y,P).
然而,
?- path(bedroom1, stairs, P).
是假的。为什么?我们不应该与 R1 匹配吗
X = bedroom1
Y = stairs
Z = hall
P = []
自从,
?- neighbor(bedroom1, hall).
true.
?- not(member(hall, [])).
true.
?- path(hall, stairs, []).
true .
?
事实上,如果我评估
?- path(A, B, P).
我只得到长度为 1 的解决方案。