How can I prevent duplicates in prolog

若如初见. 提交于 2019-11-28 06:22:04

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!