Prolog: “findall” for limited number of solutions

后端 未结 9 883
暖寄归人
暖寄归人 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:17

    There are many similar uses, so maybe consider to define some abstractions in between. E.g. call_firstn(Goal_0,N) which succeeds for at most the firstN many answers of Goal_0. This in turn can be implemented using call_nth(Goal_0, Nth).

    findfirstn(N, Template, Goal_0, Instances) :-
       findall(Template, call_firstn(Goal_0, N), Instances).
    
    call_firstn(Goal_0, N) :-
       N + N mod 1 >= 0, % ensures that N >=0 and N is an integer
       call_nth(Goal_0, Nth),
       ( Nth == N -> ! ; true ).
    

    A full implementation of call_nth/2 that does not leak and still is reentrant cannot be defined in ISO Prolog directly. You need to resort to all kinds of low-level operations with often incomplete semantics that are better hidden from the regular programmer.

提交回复
热议问题