Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog looping though variable results

Tags:

loops

prolog

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.

like image 834
Kyle G Avatar asked Nov 08 '09 14:11

Kyle G


3 Answers

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)).
like image 52
Kaarel Avatar answered Oct 05 '22 23:10

Kaarel


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.

like image 35
nedned Avatar answered Oct 05 '22 23:10

nedned


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).
like image 41
Vincent Ramdhanie Avatar answered Oct 05 '22 22:10

Vincent Ramdhanie