2014-10-22 65 views
2

我想過濾序列表中的列表,使[[a,b,c],[],[d],[e,f]]給出[[a,b,c], [E,F],我的濾波器函數應該忽略長度的元素少於兩個, 我嘗試是如下的代碼,過濾列表序列

omitunwanted([],_) :- []. 
omitunwanted([List|L1],[H|T]) :- 
    ( length(List,0)-> 
     omitunwanted(L1,[H|T]) 
    ; length(List,1)-> 
     omitunwanted(L1,[H|T]) 
    ; append(List,[],H), 
     omitunwanted(L1,T) 
    ). 

它返回輸出[[A,b,C],[對於[[a,b,c],[],[d],[e,f]]輸入[e,f] | _G1622]。我無法弄清楚我做錯了什麼

回答

4

這是一個純粹的版本,甚至適用於其中@墊的版本產生乾淨instantiation_error這些情況。

length_less_than_two_truth([], true). 
length_less_than_two_truth([_], true). 
length_less_than_two_truth([_,_|_], false). 

texclude( _, [], []). 
texclude(CT, [E|Es], Fs0) :- 
    call(CT,E,Truth), 
    ( Truth = true, 
     Fs0 = Fs 
    ; Truth = false, 
     Fs0 = [E|Fs] 
    ), 
    texclude(CT, Es, Fs). 

?- texclude(length_less_than_two_truth, [X,[a,b,c]],Ls). 
X = [], 
Ls = ["abc"] ; 
X = [_A], 
Ls = ["abc"] ; 
X = [_A, _B|_C], 
Ls = [[_A,_B|_C], "abc"] ; 
false. 

使用library(double_quotes)

3

考慮使用exclude/3。例如:

length_less_than_two(Ls) :- 
    must_be(list, Ls), 
    length(Ls, L), 
    L < 2. 

樣品查詢及其結果:

?- exclude(length_less_than_two, [[a,b,c],[],[d],[e,f]], Ls). 
Ls = [[a, b, c], [e, f]] 
+0

它的作品,你能告訴我什麼must_be/2呢? – sand 2014-10-22 08:37:57

+1

在這種情況下,'must_be'確保列表被充分實例化,以便我們可以可靠地決定是否排除它。如果你省略'must_be/2'目標,例如當列表是[X,[a,b,c]]'時,你將做出錯誤的決定。 – mat 2014-10-22 09:34:18

2

在這個答案,我們需要在同一行this previous answer

以此爲起點考慮下面的查詢:

 
?- texclude(length_less_than_two_truth, [[a,b,c],[],[d],[e,f]], Xs). 
    Xs = [[a,b,c],[e,f]]   % succeeds, but leaves choicepoint behind 
; false. 

我們可以對上面的查詢得手確定性,同時保持是的!

我們適應texclude/3length_less_than_two_t/2利用第一個參數索引:

texclude(P_2,Es,Fs) :- 
    list_texclude_(Es,Fs,P_2). 

list_texclude_([],[],_). 
list_texclude_([E|Es],Fs0,P_2) :- 
    if_(call(P_2,E), Fs0 = Fs, Fs0 = [E|Fs]), 
    list_texclude_(Es,Fs,P_2). 

length_less_than_two_t([],true). 
length_less_than_two_t([_|Es],T) :- 
    =(Es,[],T). 

注意的length_less_than_two_t/2第二條是基於 (=)/3

使用這種實現,讓我們重新運行了OP的問題查詢:

 
?- texclude(length_less_than_two_t, [[a,b,c],[],[d],[e,f]], Xs). 
Xs = [[a,b,c],[e,f]].   % succeeds deterministically