Prolog: “findall” for limited number of solutions

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

    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].
    

提交回复
热议问题