如果您的Prolog有某种非backtrackable分配的,就像SWI-Prolog的'global' variables,你可以实现(注意,头脑简单的代码)以这样的方式
:- meta_predicate solutions(0, ?).
:- meta_predicate solutions(+, 0, ?).
solutions(G, L) :-
solutions(G, G, L).
solutions(P, G, L) :-
(nb_current(solutions_depth, C) -> true ; C=1),
D is C+1,
nb_setval(solutions_depth, D),
atom_concat(solutions_depth_, D, Store),
nb_setval(Store, []),
( G,
nb_getval(Store, T),
nb_setval(Store, [P|T]),
fail
; nb_getval(Store, R)
),
nb_delete(Store),
nb_setval(solutions_depth, C),
reverse(R, L).
的“全局”变量导致用法更高效的执行WRT动态数据库(assert/retract),以及(在SWI-prolog中)甚至可以在多线程应用程序中使用。
编辑
由于@false评论,移动的切割(多个)之前反向/ 2,并且引入了一个堆栈重入调用:例如
?- solutions(X-Ys,(between(1,3,X),solutions(Y,between(1,5,Y),Ys)),S).
S = [1-[1, 2, 3, 4, 5], 2-[1, 2, 3, 4, 5], 3-[1, 2, 3, 4, 5]].
编辑
下面是解决方案/ 3的变体,按顺序构建结果列表,以避免最终的反向/ 2调用。将结果添加到列表尾部有点棘手...
solutions(P, G, L) :-
(nb_current(solutions_depth, C) -> true ; C=1),
D is C+1,
nb_setval(solutions_depth, D),
atom_concat(solutions_depth_, D, Store),
( G,
(nb_current(Store, U/B) -> B = [P|R], Q = U/R ; Q = [P|T]/T),
nb_setval(Store, Q),
fail
; (nb_current(Store, L/[]) -> true ; L = [])
),
nb_delete(Store),
nb_setval(solutions_depth, C).
是否有意义反映找到的解决方案的顺序? – false