如何让 Prolog 解释超出真实陈述的结果

adh*_*dhg 5 prolog

我有以下事实和规则:

  flight(sea,msp).
  flight(msp,jfk).

 route(A,B) :- flight(A,B). 
 route(B,A) :- flight(A,B). 
 route(A,C) :- flight(A,B) , flight(B,C). 
Run Code Online (Sandbox Code Playgroud)

当查询route(sea,jfk)我得到结果true但我希望得到的是解释:

sea-->msp-->jfk 这样我不仅可以告诉它它是真的,而且可以告诉它它是如何真实的。

Nic*_*rey 2

您可以跟踪图表中您已经访问过的节点。无论如何,您都需要这样做,因为您需要检测图中的循环,以免陷入无限递归的兔子洞。

在 Prolog 中,我们使用辅助方法将状态作为 1 个或多个额外参数携带。一个经常使用的约定是有一个“公共”谓词——比如route/3调用一个具有相同名称和更高数量的“私有”工作者谓词,比如route/4。像这样的事情应该做你:

route( A , B , R  ) :- % find a route R from A to B
  route(A,B,[],R)      % - by invoking a worker, seeding its list of visited nodes with the empty list
  .                    % Easy!

route(B,B,V,R) :-    % we've arrived at the destination (B) when the origination node is the same as the destination node.
  reverse([B|V],R)   % - just reverse the list of visited nodes to get the routing.
  .                  %
route(A,B,V,R) :-    % otherwise...
  flight(A,T) ,      % - if there's an edge out of the current node (A) ,
  \+ member(T,V) ,   % - to an as-yet unvisited node...
  route(T,B,[A|V],R) % - go visit that node, marking the current node as visited.
  .                  % Easy!
Run Code Online (Sandbox Code Playgroud)