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
This is how you would do it in ECLiPSe:
find_n(N, Term, Goal, Solutions) :-
( N < 1 ->
Solutions = []
;
record_create(Bag),
shelf_create(count(N), Counter),
(
once((
call(Goal),
recordz(Bag, Term),
\+shelf_dec(Counter, 1) % succeed if enough
)),
fail
;
recorded_list(Bag, Solutions)
)
).
This is reentrant and does not leak memory (both are problems with global variable or dynamic predicate based solutions). Small additions are needed if you want it to deal correctly with modules.
You could of course use the same code structure with the assert/retract primitives that Paulo used.