Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog: "findall" for limited number of solutions

Tags:

prolog

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.

like image 328
Sergii Dymchenko Avatar asked Dec 31 '13 06:12

Sergii Dymchenko


1 Answers

SWI-Prolog offers the built-in predicates findnsols/4 and findnsols/5

?- findnsols(5, I, between(1, 12, I), L).
L = [1, 2, 3, 4, 5] ;
L = [6, 7, 8, 9, 10] ;
L = [11, 12].

You may want to wrap the whole call in once/1 to prevent backtracking for further solution groups (e.g. if in the example above you want the 1-5 list to be your ONLY solution).

?- once( findnsols(5, I, between(1, 12, I), L) ).
L = [1, 2, 3, 4, 5].
like image 145
Kaitain Avatar answered Oct 07 '22 23:10

Kaitain