My multiple solution problem arises due to Prolog's backtracking looping through the goals. Whilst I understand that, technically, each solution provided is correct, it is not useful to me. Is there a method to remove duplicates?
Here is my code so far:
flight(london, paris).
flight(paris, amsterdam).
flight(amsterdam, rome).
flight(rome, paris).
flight(rome, rio_de_janeiro).
route_from(A,B) :-
flight(A,B).
route_from(A,B) :-
flight(A,R),
route_from(R,B).
An example query is:
?- route_from(A, paris).
A = london ;
A = rome ;
A = london ;
A = london ;
A = london ;
A = london ;
A = london ;
A = london ;
A = london ;
etc.
Regards.
You have a bigger issue other than returning repeated solutions. Your program, as is, will loop indefinitely as there are loops in your graph.
To avoid loops you may maintain a list of visited cities:
route_from(A,B) :-
route_from(A,B, []).
route_from(A,B, _) :-
flight(A,B).
route_from(A,B, Visited) :-
flight(A,R),
\+ member(A, Visited),
route_from(R,B, [A|Visited]).
Now, this won't prevent returning duplicates if there are more than one way to go to a city. You can use setof/3
+ member/2
to gather all solutions without duplicates.
route_from_without_duplicates(A,B):-
setof(A-B, route_from(A,B), Routes),
member(A-B, Routes).
来源:https://stackoverflow.com/questions/16243081/how-can-i-prevent-duplicates-in-prolog