保持逻辑上的纯粹和高效。如何?通过使用元谓词tpartition/4
和(#=<)/3
!
首先,让我们定义(#=<)/3
的具体化版本(#=<)/2
,基于bool01_t/2
。
为了完整起见,我们还要定义(#<)/3
,(#>)/3
和(#>=)/3
!
#=<(X,Y,Truth) :- X #=< Y #<==> B, bool01_t(B,Truth).
#<( X,Y,Truth) :- X #< Y #<==> B, bool01_t(B,Truth).
#>( X,Y,Truth) :- X #> Y #<==> B, bool01_t(B,Truth).
#>=(X,Y,Truth) :- X #>= Y #<==> B, bool01_t(B,Truth).
就是这样!现在,让我们进行 OP 想要的拆分:
?- tpartition(#=<(0),[1,-2,3,4,-8,0],Ts,Fs).
Ts = [1,3,4,0], Fs = [-2,-8]. % succeeds deterministically
这是单调的,因此即使使用一般的非基本术语,我们也会得到正确的答案:
?- tpartition(#=<(0),[A,B,C],Ts,Fs).
Ts = [ ], Fs = [A,B,C], A in inf.. -1, B in inf.. -1, C in inf.. -1 ;
Ts = [ C], Fs = [A,B ], A in inf.. -1, B in inf.. -1, C in 0..sup ;
Ts = [ B ], Fs = [A, C], A in inf.. -1, B in 0..sup, C in inf.. -1 ;
Ts = [ B,C], Fs = [A ], A in inf.. -1, B in 0..sup, C in 0..sup ;
Ts = [A ], Fs = [ B,C], A in 0..sup, B in inf.. -1, C in inf.. -1 ;
Ts = [A, C], Fs = [ B ], A in 0..sup, B in inf.. -1, C in 0..sup ;
Ts = [A,B ], Fs = [ C], A in 0..sup, B in 0..sup, C in inf.. -1 ;
Ts = [A,B,C], Fs = [ ], A in 0..sup, B in 0..sup, C in 0..sup .
编辑 2015-06-02
如果我们partition/4
在上述查询中使用 SWI-Prolog 库谓词会怎样?
?- partition(#=<(0),[A,B,C],Ts,Fs).
Ts = [A,B,C], Fs = [], A in 0..sup, B in 0..sup, C in 0..sup.
我们将失去 8 个解决方案中的 7 个,因为partition/4
不是单调的!