1

我有一个问题,我有两个列表,我想提取所有相同的元素。例如 :

> 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].

但是我制作的这段代码不起作用。我是新手,所以...有什么问题?:/

4

3 回答 3

2

您正在使用累加器,因此代码应该是

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).
于 2012-12-30T19:14:54.110 回答
2

交集/3 正是你需要的。

?- intersection([la_defense,etoile,chatelet,nation],[auber,chatelet,hotel_de_ville,nation],X).
X = [chatelet, nation].
于 2012-12-30T21:22:01.643 回答
1

对类似问题Intersection and union of 2 个列表的回答可能会让您感兴趣。

与这里和那里发布的其他答案不同,我建议的实现在逻辑上是纯粹的和单调的,这使得它在泛化/专业化方面更加通用和健壮。

首先,让我们看看它是否适用于您上面给出的查询:

?- 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不是monotone

底线: intersection/3比正确使用更难list_list_intersection/3;它迫使您在使用它时考虑声明性和程序性方面。

于 2015-04-29T11:09:24.430 回答