Prolog: “findall” for limited number of solutions

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

    I think you will need to manually implement the uniqueness condition that is implied in findall, i.e., you will need to aggregate solutions and for each new one check that it hasn't yet been picked before.

    Here is an example of how this can work:

    %% an example predicate with infinite solutions
    find(0).
    find(X) :- find(X1), X is X1+1.
    
    %% myfindall(+Num) holds when there are at least Num different solutions for find
    myfindall(Num) :-
        length(L, Num),
        mfa_aux(L, [], All),
        %% now do something with All, e.g., sum it.
        writeln(All).
    
    mfa_aux([], All, All).
    mfa_aux([H|T], All, Rtv) :-
        find(H),
        not(member(H, All)), !,
        mfa_aux(T, [H|All], Rtv).
    
    
    %% Test
    %% ?- myfindall(10).
    

提交回复
热议问题