Prolog: “findall” for limited number of solutions

后端 未结 9 882
暖寄归人
暖寄归人 2020-12-06 17:36

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

9条回答
  •  再見小時候
    2020-12-06 18:19

    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.

提交回复
热议问题