Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the nth solution of a query

Tags:

prolog

Can I extract the nth solution of a query? I'm aware of findall, but I think (correct me if I'm wrong) that it creates an entire list of solutions, and I'd prefer an approach that consumes only as much memory as needed to compute the value.

like image 678
András Kovács Avatar asked Nov 09 '22 19:11

András Kovács


1 Answers

Here is a simple way in which you can let SWI-Prolog calculate exactly N solutions (where you can supply the number N yourself).

In this example N is 17 and the goal whose 17th solution we're interested in is between(0, inf, I):

?- findnsols(17, I, between(0, inf, I), L), last(L, X), !.
L = [0, 1, 2, 3, 4, 5, 6, 7, 8|...],
X = 16.

Notice the use of the cut in order to force determinism. With the cut findnsols/4 may be used for pagination (i.e., in order to calculate the next 17 solutions).

like image 60
Wouter Beek Avatar answered Nov 15 '22 10:11

Wouter Beek