A 逻辑纯粹实施非常简单,感谢clpfd /questions/tagged/clpfd:
:- use_module(library(clpfd)).
list_evens_odds([],[],[]).
list_evens_odds([X|Xs],[X|Es],Os) :-
X mod 2 #= 0,
list_evens_odds(Xs,Es,Os).
list_evens_odds([X|Xs],Es,[X|Os]) :-
X mod 2 #= 1,
list_evens_odds(Xs,Es,Os).
一些样本我们期望成功的查询(具有有限的答案序列):
?- Xs = [1,2,3,4,5,6,7], list_evens_odds(Xs,Es,Os).
Xs = [1,2,3,4,5,6,7],
Es = [ 2, 4, 6 ],
Os = [1, 3, 5, 7] ;
false.
?- list_evens_odds(Ls,[2,4],[1,3]).
Ls = [2,4,1,3] ? ;
Ls = [2,1,4,3] ? ;
Ls = [2,1,3,4] ? ;
Ls = [1,2,4,3] ? ;
Ls = [1,2,3,4] ? ;
Ls = [1,3,2,4] ? ;
no
关于什么我们预计会失败的查询?
?- list_evens_odds(Ls,[2,4,5],[1,3]).
no
?- list_evens_odds(Ls,[2,4],[1,3,6]).
no
?- list_evens_odds([_,_,_],[2,4],[1,3]).
no
最后,最一般的查询:
?- assert(clpfd:full_answer).
yes
?- list_evens_odds(Ls,Es,Os).
Ls = [], Es = [], Os = [] ? ;
Ls = [_A], Es = [_A], Os = [], _A mod 2#=0, _A in inf..sup ? ...
编辑2015-05-06
这是另一种方法逻辑纯粹性 /questions/tagged/logical-purity!
使用元谓词tpartition/4 https://stackoverflow.com/a/29867514/4609915和...一起zeven_t/2
or zodd_t/2
.
bool01_t(1,true).
bool01_t(0,false).
zeven_t(Z,Truth) :- Z mod 2 #= 0 #<==> B, bool01_t(B,Truth).
%zodd_t(Z,Truth) :- Z mod 2 #= 1 #<==> B, bool01_t(B,Truth).
zodd_t(Z,Truth) :- Z mod 2 #= B, bool01_t(B,Truth). % tweaked
zeven_t/2
具体化了evenness一个整数,zodd_t/2
the oddness.
一切就绪后,让我们运行一些查询!
?- tpartition(zeven_t,[1,2,3,4,5,6,7],Es,Os).
Es = [2,4,6], Os = [1,3,5,7].
?- tpartition(zodd_t ,[1,2,3,4,5,6,7],Os,Es). % argument order differs
Es = [2,4,6], Os = [1,3,5,7].
Both 确定性地成功。等效查询使用list_evens_odds/3
才不是。