我想教自己序言。下面,我寫了一些代碼,我認爲它應該返回無向圖中節點之間的所有路徑......但事實並非如此。我試圖理解爲什麼這個特定的代碼不起作用(我認爲這個問題與類似的Prolog尋路帖不同)。我在SWI-Prolog中運行它。任何線索?在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).
IFF A - >乙 - 「ç - > 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的解決方案。