Prolog: "findall" for limited number of solutions

Viewed 2680

Say I want to find sum of all solutions to a predicate, I just can use

findall(L, find(L), Sols),

and just sum members of Sols.

But what if find(L) has a huge number (infinitely, maybe) of solutions, and I just want to get only first 10 of them?

I'd want this to be usable in B-Prolog and ECLiPSe CLP.

9 Answers

You can combine findall/3 with limit/2 from the library solution sequence, inspired from SQL:

limit(+Count, :Goal)
Limit the number of solutions
https://www.swi-prolog.org/pldoc/man?predicate=limit/2

Here is an example run:

?- findall(X, limit(3, (repeat, X = 1)), L).
L = [1, 1, 1].

A couple of Prolog systems have predicates like limit/2 in their repertoire.

Related