Route planning in Prolog

2019-07-12 13:06发布

问题:

Here is a route planning program given by an online tutorial:-

route(X,Y,R) :-
 route(X,Y,[X],R).

route(X,Y,_,[drive(X,Y)]) :-
 travel(X,Y).
route(X,Y,V,[drive(X,Z)|R]) :-
 travel(X,Z),
 \+ member(Z,V),
 route(Z,Y,[Z|V],R)
 Z \= Y.     %Only required if Y is not ground.


travel(X,Y) :- road(X,Y).
travel(X,Y) :- road(Y,X). 


road(arad,sibiu).
road(arad,timisoara).
road(arad,zerind).
road(zerind,oradea).
road(oradea,sibiu).
road(sibiu,fagaras).

What I do not understand is the commented statement: Z\=Y. Why this statement is needed? And why that statement is only needed if Y is not ground?

回答1:

The Z \= Y line prevents loops in the route otherwise you could have a segement that was arad -> arad.



标签: prolog