我已经询问过有关旅行的问题,
byCar(auckland,hamilton).
byCar(hamilton,raglan).
byCar(valmont,saarbruecken).
byCar(valmont,metz).
byTrain(metz,frankfurt).
byTrain(saarbruecken,frankfurt).
byTrain(metz,paris).
byTrain(saarbruecken,paris).
byPlane(frankfurt,bangkok).
byPlane(frankfurt,singapore).
byPlane(paris,losAngeles).
byPlane(bangkok,auckland).
byPlane(losAngeles,auckland).
我修改了这个:
connect(X,Y,byCar):- byCar(X,Y) ; byCar(Y,X).
connect(X,Y,byTrain):- byTrain(X,Y) ; byTrain(Y,X).
connect(X,Y,byPlane):- byPlane(X,Y) ; byPlane(Y,X).
travel(X,Y):-X\=Y,travelLoop(X,Y,Passed).
travelLoop(X,Y,Passed):-connect(X,Thru,byCar);
connect(X,Thru,byTrain);
connect(X,Thru,byPlane);
\+memberchk(Thru,Passed),travelLoop([Thru|Passed],Y,Thru).
travelLoop(X,Y,Path):- X=Y.
travel(X,Y):-travel_Path(X,Y,[X]),
travel_Path(Y,X,[Y]) -> true ; wrong.
wrong:- writeln('Wrong travel input, please try again.'), nl.
效果很好。我可以再问一次,这是能够显示所有替代旅行路径,来回。只是设法以一种方式获得它。
(c)
travel(X,Y,go(X,Y)):-byCar(X,Y).
travel(X,Y,go(X,Y)):-byTrain(X,Y).
travel(X,Y,go(X,Y)):-byPlane(X,Y).
travel(X,Y,go(X,Z,W)):-travel(X,Z,go(X,Z)),travel(Z,Y,W).
findall(X,travel(A,B,X),List),nl,
writelist(List).
writelist([]).
writelist([L|Lt]):-write(L),nl,writelist(Lt).
(d)
travel1(X,Y,go(X,Y,car)):-byCar(X,Y).
travel1(X,Y,go(X,Y,train)):-byTrain(X,Y).
travel1(X,Y,go(X,Y,plane)):-byPlane(X,Y).
travel1(X,Y,go(X,Z,V,W)):-travel1(X,Z,go(X,Z,V)),travel1(Z,Y,W).
findall(Y,travel1(A,B,Y),List1),nl,
writelist(List1).
writelist([]).
writelist([L|Lt]):-write(L),nl,writelist(Lt).
有什么建议吗?
(c)的输出,如果我输入from=valmont, to=paris
,它会给出:
go(valmont,saarbruecken,go(saarbruecken,paris))
go(valmont,metz,go(metz,paris))
(d)的情况相同。
go(valmont,saarbruecken,car,go(saarbruecken,paris,train))
go(valmont,metz,car,go(metz,paris,train))