Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all the solutions to a predicate in Prolog

Tags:

prolog

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?

like image 457
Kai Avatar asked May 10 '09 21:05

Kai


People also ask

How do you get multiple answers in Prolog?

The user can type the semi-colon (;) or spacebar, if (s)he wants another solution. Use the return key if you do not want to see the more answers. Prolog completes the output with a full stop (.) if the user uses the return key or Prolog knows there are no more answers.

What is S () in Prolog?

They are just terms, a representation of the successor of their argument. So, s(0) is used to represent the successor of 0 (i.e. 1 ), s(s(0)) is used to represent the successor of s(0) (i.e. 2 ), and so on and so forth.

What does \+ mean in Prolog?

Because of the problems of negation-as-failure, negation in Prolog is represented in modern Prolog interpreters using the symbol \+ , which is supposed to be a mnemonic for not provable with the \ standing for not and the + for provable.


1 Answers

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))
like image 128
Volodymyr Gubarkov Avatar answered Nov 03 '22 01:11

Volodymyr Gubarkov