Getting all the solutions to a predicate in Prolog

独自空忆成欢 提交于 2020-01-13 02:55:49

问题


I'm writing a text adventure game in Prolog, and I am printing out room exits. I have code that does:

exits_from(Room) :-
  connected(Room, X),
  write(X), write('  ').

where connected/2 is:

connected(X, Y) :- path(X, Y).
connected(X, Y) :- path(Y, X).

and path is:

path(room, hallway).
path(hallway, foyer).

and so on.

When I am printing the exits for a room though, it gets the first, then wants a ';' to say that I want another solution. Is there anyway to force a predicate to compute the result entirely, so that the player wouldn't have to keep asking for more exits?


回答1:


one way is to do something like

print_all_solutions :-
  solution(Sol),
  write(Sol),
  fail. % this causes backtracking
print_all_solutions. % succed

another is to use special predicate forall, like follows:

forall(solution(Sol), write(Sol))


来源:https://stackoverflow.com/questions/846145/getting-all-the-solutions-to-a-predicate-in-prolog

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