2012-12-30 78 views
1

我有一個問題,我有兩個列表,我想提取所有相同的元素。例如:Prolog - 在兩個列表中提取元素列表

> comparer([la_defense,etoile,chatelet,nation],[auber,chatelet,hotel_de_ville,nation],X). 

comparer([],LSB,LI). 
comparer([X|LS],LSB,LI):-member(X,LSB),!,comparer(LS,LSB,[LI|X]). 
comparer([X|LS],LSB,LI):-comparer(LS,LSB,LI). 

我想這樣的結果:

X = [chatelet,nation]. 

但這個代碼,我做不工作。我是新手,所以......問題是什麼? :/

回答

2

您使用的是accumlator,所以代碼應該是

comparer(L1, L2, R) :- 
    comparer(L1, L2, [], R). 

comparer([], _, R, LR) :- 
    reverse(R, LR). 

comparer([X|LS],LSB,LI, R):- 
    member(X,LSB),!, 
    comparer(LS,LSB,[X | LI], R). 
comparer([_X|LS],LSB,LI, R):- 
    comparer(LS,LSB,LI, R). 

你可以試試這個

comparer([], _, []). 

comparer([X|LS],LSB,LI):- 
    comparer(LS, LSB, R), 
    ( member(X, LSB) -> LI = [X | R]; LI = R). 
+0

謝謝,它完美的作品^^所以如果成員是真的,LI = [X | R] ...被執行?我不知道「 - >」:/ – toshiro92

2

intersection/3不正是你需要的。

?- intersection([la_defense,etoile,chatelet,nation],[auber,chatelet,hotel_de_ville,nation],X). 
X = [chatelet, nation]. 
+0

我不明白你想解釋什麼? – toshiro92

+1

以防萬一您不知道可用的庫... IMO是有意義的,因爲@ joel76已經解決了代碼中的問題 – CapelliC

1

My answer到類似的問題Intersection and union of 2 lists可能是你的興趣。

與此處發佈的其他答案和there不同,我建議的實現邏輯上是純粹的和單調的,這使得它在泛化/專業化方面更加通用和強大。

首先,讓我們看看它是否與您在上面給了查詢工作:

?- As = [la_defense,etoile,chatelet,nation], 
    Bs = [auber,chatelet,hotel_de_ville,nation], 
    list_list_intersection(As,Bs,Xs). 
As = [la_defense, etoile, chatelet, nation], 
Bs = [auber, chatelet, hotel_de_ville, nation], 
Xs = [chatelet, nation]. 

但是,如果我們寫在不同的(但邏輯上等同)的方式查詢?

?- As = [_,_,_,_], 
    Bs = [_,_,_,_], 
    list_list_intersection(As,Bs,Xs), 
    As = [la_defense,etoile,chatelet,nation], 
    Bs = [auber,chatelet,hotel_de_ville,nation]. 
As = [la_defense, etoile, chatelet, nation], 
Bs = [auber, chatelet, hotel_de_ville, nation], 
Xs = [chatelet, nation]. 

隨着list_list_intersection/3我們得到相同的結果


現在,讓我們考慮使用內置intersection/3,這是在另一個答案建議。關於泛化也是intersection/3強健嗎?

?- As = [_,_,_,_], 
    Bs = [_,_,_,_], 
    intersection(As,Bs,Xs), 
    As = [la_defense,etoile,chatelet,nation], 
    Bs = [auber,chatelet,hotel_de_ville,nation]. 
false. 

不!intersection/3失敗,儘管它在邏輯上等價的查詢成功了,這表明intersection/3的執行是而非單調

底線:intersection/3更難使用權list_list_intersection/3;它迫使你在使用它時考慮聲明性程序方面的