:- use_module(library(assoc)). f([(N-N)|X],N) :- N > 0 -> (NN is N - 1, f(X,NN)) ; X=[]. runner1(N,A,S) :- N > 0 -> (get_assoc(N,A,V), SS is S + V, NN is N - 1, runner1(NN,A,SS)) ; (write(res(S)), nl). do1(N,M,A) :- M > 0 -> (runner1(N,A,0), MM is M - 1, do1(N,MM,A)) ; true. run1(N,M) :- once((f(L,N), list_to_assoc(L,A), do1(N,M,A))).