Getting all the solutions to a predicate in Prolog

2019-04-09 05:25发布

问题:

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))


标签: prolog