How can I prevent duplicates in prolog

妖精的绣舞 提交于 2019-11-29 12:22:12

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