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
Needing to make a thread-safe solution in SWI Prolog, I came with this:
find_n( N, Solution, Goal, Solutions ) :-
thread_self( Thread_id ),
atomic_list_concat( [counter, Thread_id], Counter_flag_key ),
flag( Counter_flag_key, _, 0 ),
findall( Solution, (
call( Goal ),
flag( Counter_flag_key, X, X ),
X1 is X + 1,
flag( Counter_flag_key, _, X1 ),
( X1 >= N -> !; true )
), Solutions ).