我正在尝试自学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).
为什么会是false呢?难道我们不应该通过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的解决方案。