tags:

views:

261

answers:

3

Hello,

I have a small program wrote in prolog. At the moment I can print the first result with

test(X, 1, 4, 5).

write(X).

But if there is more than one result for X, How do I print the next ones?

Thanks

~ KyleG

+1  A: 

Do you mean automatically? You can issue a backtrack command with ; and it backtracks and gets the next value. But if you want to print multiple results within the program then you use recursion. Give some more details of what you are trying to do.

UPDATE: You cannot issue ;. You have to write a procedure to "loop" through the results, so you may want the results in a list.

   printList([]) :- write("").
   printList([H|T]) :- write(H), printList(T).
Vincent Ramdhanie
I want the application to issue to ; command to loop though the results.
Kyle G
The example contains a syntax error: replace ';' with '.'. But even after fixing this error, the program does not work correctly, e.g. "?- printList([a, b, c])." outputs "abc[]" where the trailing "[]" is probably not wanted.
Kaarel
+2  A: 

If you want to get every solution for a variable in a call without having to continuously press ';' for the next solution, you can use the findall predicate like this:

findall(X,test(X,1,4,5),L).

The first argument specifies which variable you would want to collect all the values of, the second argument is the predicate along with its arguments that you want to find all the solutions for, and the third argument will be a list of all the values of X from all of the solutions.

So from here, you can can just print the values of L if you're happy with the result being formatted as a list. Otherwise you will need need to write a recursive predicate to print the contents of L in the way you want, as Vincent Ramdhanie points out.

humble coffee
+3  A: 

Use a failure-driven loop:

test(X, 1, 4, 5), writeln(X), fail ; true.

or the same in a more readable way, using forall/2:

forall(test(X, 1, 4, 5), writeln(X)).

There is no need to construct a list of all the solutions (this is what findall/3 is for), unless you need this list for something else than just printing it out.

Kaarel