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.
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.
If your Prolog doesn't have forall/2
then implement it yourself in the following way:
forall(A, B) :-
\+ (call(A), \+ call(B)).
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With