Prolog: “findall” for limited number of solutions

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

    Needing to make a thread-safe solution in SWI Prolog, I came with this:

    find_n( N, Solution, Goal, Solutions ) :-
        thread_self( Thread_id ),
        atomic_list_concat( [counter, Thread_id], Counter_flag_key ),
        flag( Counter_flag_key, _, 0 ),
    
        findall( Solution, (
    
            call( Goal ),
    
            flag( Counter_flag_key, X, X ),
            X1 is X + 1,
            flag( Counter_flag_key, _, X1 ),
    
            ( X1 >= N -> !; true )
    
        ), Solutions ).
    

提交回复
热议问题