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.
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).
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