% link(Origin,Destination,Speed,Length).
link(paris,milano,140,360).
link(paris,london,200,698).
link(berlin,atena,110,714).
link(atena,paris,90,370).
我需要写这个路线谓词,所以我从城市X到城市Y得到Path
。
route(Origin,Destination,TrainType,Path,Length,Duration).
我是Prolog的新手,所以我写了这样的东西。我知道这不对:
route(Origin,Destination,TrainType,Path,Legth,Duration) :-
link(Origin,City,Len),
City \= Origin,
NewLen is Length + Len,
route(City,Destination,TrainType,Path,NewLen,Duration).
答案 0 :(得分:2)
您的谓词缺少基本情况,告诉它何时停止。现在,你的谓词将一直调用自己,直到它失败(或更糟糕的是,无限循环,取决于你的link
谓词)。以下为您提供了反向路径:
route(Goal, Goal, Path, Path). % base case
route(From, To, Path0, Path) :-
direct_link(From, Via),
route(Via, To, [From|Path0], Path).
直接链接意味着您可以从A到B;我假设铁路是双向的:
direct_link(A,B) :- link(A, B, _Speed, _Length).
direct_link(B,A) :- link(B, A, _Speed, _Length).
您需要在路径上调用reverse
并添加参数以跟踪长度和持续时间。我会把它留作练习。