Help finding paths
% 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).
I need to write this route predicate so I get a Path
from city X to city Y.
route(Origin,Destination,TrainType,Path,Length,Dur开发者_运维技巧ation).
I am new to Prolog, so I wrote something like this. I know it's not correct:
route(Origin,Destination,TrainType,Path,Legth,Duration) :-
link(Origin,City,Len),
City \= Origin,
NewLen is Length + Len,
route(City,Destination,TrainType,Path,NewLen,Duration).
Your predicate lacks a base case, that tells it when to stop. Right now, your predicate will always call itself until it fails (or worse, loops indefinitely, depending on your link
predicate). The following gives you a reverse path:
route(Goal, Goal, Path, Path). % base case
route(From, To, Path0, Path) :-
direct_link(From, Via),
route(Via, To, [From|Path0], Path).
where a direct link means you can get from A to B; I'm assuming railways are bidirectional:
direct_link(A,B) :- link(A, B, _Speed, _Length).
direct_link(B,A) :- link(B, A, _Speed, _Length).
You will need to call reverse
on the path and add arguments to keep track of length and duration. I'll leave that as an exercise.
精彩评论