Prolog - 使用迭代器回溯
Prolog - backtracking with iterator
我有一个谓词:
solve(parts(X), Places) :-
"iterate Pl from Places to 0",
tryPutPart(X, Pl),
fail.
我想在那里强制回溯,因为我想要所有可能的解决方案。(相反,我会在不同的谓词中递归地找到位置 Pl)。
有办法做到吗?我的想法是制作一个长度为 Places
并且看起来像 [1, 2, 3.....]
的列表,然后尝试从中不确定地输出一些 Y。
我想要的行为是,如果我将 places(0). places(1). places(2). - ... -
等写入代码,然后像
那样编写
:- places(Y), tryPutPart(X, Y).
对于这个问题,我使用了谓词for
for(M,M,N):- M < N.
for(I,M,N):- M < N, M1 is M + 1, for(I,M1,N).
然后就可以强制回溯了:
solve(parts(X),Places) :- for(Y, 1, TPlaces), tryPutPart(X, Y), fail.
您可以使用 between/3
谓词检查给定范围内的所有整数。例如:
?- between(1, 10, N), N > 3, write(N), nl, fail.
4
5
6
7
8
9
10
false.
有关此谓词的 SWI-Prolog 文档,请参阅 http://www.swi-prolog.org/pldoc/doc_for?object=between/3。
我有一个谓词:
solve(parts(X), Places) :-
"iterate Pl from Places to 0",
tryPutPart(X, Pl),
fail.
我想在那里强制回溯,因为我想要所有可能的解决方案。(相反,我会在不同的谓词中递归地找到位置 Pl)。
有办法做到吗?我的想法是制作一个长度为 Places
并且看起来像 [1, 2, 3.....]
的列表,然后尝试从中不确定地输出一些 Y。
我想要的行为是,如果我将 places(0). places(1). places(2). - ... -
等写入代码,然后像
:- places(Y), tryPutPart(X, Y).
对于这个问题,我使用了谓词for
for(M,M,N):- M < N.
for(I,M,N):- M < N, M1 is M + 1, for(I,M1,N).
然后就可以强制回溯了:
solve(parts(X),Places) :- for(Y, 1, TPlaces), tryPutPart(X, Y), fail.
您可以使用 between/3
谓词检查给定范围内的所有整数。例如:
?- between(1, 10, N), N > 3, write(N), nl, fail.
4
5
6
7
8
9
10
false.
有关此谓词的 SWI-Prolog 文档,请参阅 http://www.swi-prolog.org/pldoc/doc_for?object=between/3。