如何在此图探路者的 Prolog 中显示中间步骤?

How can I show the intermediate steps in Prolog of this graph pathfinder?

我在 Prolog 中创建了这个知识库,它反映了一家巴士公司,其巴士往返于各个地方,在设定的时间出发和到达:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
connection(kerkrade, heerlen, 1100, 1200).
connection(kerkrade, bleijerheide, 1100, 1225).
connection(heerlen, kerkrade, 1115, 1230).
connection(heerlen, maastricht, 1230, 1330).
connection(maastricht, heerlen, 1430, 1530).
connection(maastricht, sittard, 1331, 1430).
connection(maastricht, sittard, 1345, 1445).
connection(sittard, maastricht, 1630, 1530).
connection(sittard, denbosch, 1530, 1700).
connection(denbosch, sittard, 1800, 1930).
connection(denbosch, amsterdam, 1000, 1330).

checkTime(X,Y,Z):-
    connection(X,Y,S,_),
    (Z =< S).

 aRoute(From, To, Time):-
    checkTime(From,To,Time).

testRoute(A,B,T):-
    walk(A,B,T,[]).


walk(A,B,Time,V) :-
    aRoute(A,X,Time),
    not(member(X,V)),
    (
        B = X;
        connection(A,X,_,S), walk(X,B,S,[A|V])
    ).

每当我询问我的知识库是否有两点之间的路线时,它都会返回是否可行; truefalse:

1
2
3
4
testRoute(kerkrade, sittard, 900).
true; (signifies that there are three routes, of which two are possible)
true;
false.

然而,这不是我想要的。在最好的情况下,我想显示用于在顶层的两点之间创建路线的连接,如下所示:

1
2
3
connection(kerkrade, heerlen, 1100, 1200)
connection(heerlen, maastricht, 1230, 1330)
/* and so on.. */

我该怎么做?我想我必须在调用 testRoute 的同时传递一个像 X 这样的变量,以便它可以报告它的值。我无法为此编写谓词,因为我不确定将它放在哪里。我的想法是我必须向 walk(A,B,Time,V) 添加一个额外的参数,但我不知道在那之后我可以用它做什么才能让它报告路线的中间步骤。


I want to show the connections used to create the route between two points [...] How do I do this? I think I have to pass a variable like X along with my call to testRoute, so that it can report the value of it.

是的:我想你必须为路由传递另一个变量

我提出以下解决方案

1
2
3
4
5
6
7
8
9
10
11
walk(Stop, Stop, _, ReverseRoute, DirectRoute):-
  reverse(ReverseRoute, DirectRoute).

walk(Start, Stop, TimeMin, ReverseRoute, DirectRoute) :-
  connection(Start, Mid, TimeStart, TimeArrival),
  TimeMin =< TimeStart,
  not(member(Mid, ReverseRoute)),
  walk(Mid, Stop, TimeArrival, [Mid | ReverseRoute], DirectRoute).

testRoute(Start, Stop, TimeStart, Route) :-
  walk(Start, Stop, TimeStart, [Start], Route).

您可以通过以下方式保留连接列表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 checkTime(X,Y,Z, connection(X,Y,S,W)):-
    connection(X,Y,S,W),
    (Z =< S).

 aRoute(From, To, Time,Head):-
    checkTime(From,To,Time,Head).

testRoute(A,B,T,L):-
    walk(A,B,T,[],L).


walk(A,B,Tijd,V,[Head|L]) :-
    aRoute(A,X,Tijd,Head),
    not(member(X,V)),
    (
        B = X,L=[];
        connection(A,X,_,S), walk(X,B,S,[A|V],L)
    ).

示例:

1
2
3
4
?- testRoute(kerkrade, sittard, 900,L).
L = [connection(kerkrade, heerlen, 1100, 1200), connection(heerlen, maastricht, 1230, 1330), connection(maastricht, sittard, 1331, 1430)] ;
L = [connection(kerkrade, heerlen, 1100, 1200), connection(heerlen, maastricht, 1230, 1330), connection(maastricht, sittard, 1345, 1445)] ;
false.