2014-10-09 99 views
1

我想刪除list1中的元素,當它等於list2中的元素時。 查詢和預期成果是:刪除列表中的元素

filter([[1,2,3],[1]] , [[1]] , X). 
X = [[1, 2, 3]] ; 

filter([[1,2,3],[1],[2,3,4],[2]] , [[1],[2]] , X). 
X = [[1, 2, 3],[2,3,4]] ; 

我已經把現在做的是:

filter(_,[],_). 
filter([A|B],[A|D],E):- 
    filter(B,D,E). 
filter([A|B],[C|D],[A|E]):- 
    A\=C, 
    filter(B,D,E). 

但似乎不對的,並給出這樣的輸出:

11 ?- filter([[1,2,3],[1]],[[1]],X). 
X = [[1, 2, 3]|_G488] ; 

誰能幫忙?也許我接近成功。

回答

0

您的程序無法正常工作,因爲您每次都從第二個列表中刪除一個元素。你的基本情況(第一個子句)也不應該是一個沒有實際意義的變量(這就是你在輸出中給你的|_G488

你必須迭代第一個列表來過濾第二個列表中找到的元素,但不去除第二列表的元素

例如:。

filter([], _, []). 
filter([Item|L1], L2, L3):- 
    (member(Item, L2) -> L4=L3;L3=[Item|L4]), 
    filter(L1, L2, L4). 

第一化酶是遞歸的基情況下,它指出該輸出爲一個空列表將是一個空列表 第二個子句檢查輸入列表的第一個項目是否找到第二個列表。如果找到它,則不會將其添加到結果列表中;否則會被添加。然後遞歸調用自己與輸入列表的其餘部分。 但絕不會將第二個列表中的元素刪除。

-1

嘛,偷懶的方法是使用構建插件,findall/3member/2

filter(Xs , Ys , Rs) :- 
    findall(X , (member(X,Xs), \+ member(X,Ys)) , Rs) . 

它說,找到所有X這樣X是列表XsXs is *not* a member of the list Ys`的成員。

假設你的導師希望你拿出你自己的實現,你可能首先想要分解你的問題。你需要做兩件事:

  • 遍歷列表,刪除在另一個列表中找到的項目。

  • 給定一個項目,確定它是否包含在另一個列表中。

這兩個都很簡單。如果要判斷一個項目包含在一個列表,你可以這樣說:

contained_in(X , [X|Ys]) :- % if we find the item in the list, 
    ! .       % - we succeed and eliminate any alternatives. 
contained_in(X , [_|Ys]) :- % otherwise, we discard the head of the list, 
    contained_in(X,Ys) .  % - and keep looking by recursing down. 

實際的過濾非常簡單,太:

filter([]  , _ , [] ) . % once the source list is exhausted, we're done. 
filter([X|Xs] , Ys , [X|R]) :- % otherwise... 
    \+ contained_in(X,Ys) ,   % - if the current list item is not contained in the list of items to be removed, 
    ! ,        % - cut off alternatives, 
    filter(Xs , Ys , R) .   % - add the current item to the result list and recurse down. 
    .        % 
filter([_|Xs] , Ys , R) :-  % if the current list item IS contained in the list of items to be removed, 
    filter(Xs , Ys , R)   % - discard it and recurse down. 
    .        % Easy! 
-1

filter只是subtract可與許多Prolog的系統(我和B-的Prolog,SWI-Prolog的和Eclipse測試):

?- subtract([[1,2,3],[1]] , [[1]] , X). 
X = [[1, 2, 3]]. 

?- subtract([[1,2,3],[1],[2,3,4],[2]] , [[1],[2]] , X). 
X = [[1, 2, 3], [2, 3, 4]]. 

你可以看一下SWI-Prolog的或者Eclipse的實施細節的來源。