我有两个清单:
L1 = [[a,b,c], [e,b,d], [f,g,a]]
L2 = [a,e]
我想将L2与L1中的每个列表进行比较,并找到常见项目的数量。我正在尝试以下代码:
common([],L).
common([H|T], L, Out):-
intersection(H,L,Out), common(T, L, Out),
length(Out,Len).
但是,它不起作用:
?- common([[a,b,c], [e,b,d], [f,g,a]], [a,e], Outlist).
false.
主列表保留在列表中的列表中(如使用writeln语句调试后看到的那样):
L is:
[a,e]
H|T is:
[[f,g,a]]
Outlist = [] .
问题出在哪里,我该如何解决?
我编辑了要调试的代码,发现它已经开始工作了:
common([],L,Out).
common([H|T], L, Out):-
writeln('------------in common--------------'),
writeln('L is:'), writeln(L),
writeln('H is:'), writeln(H),
intersection(L,H,Out2list),
writeln('Out2list is:'), writeln(Out2list),
common(T, L, Out2).
41 ?- common([[a,b,c], [e,b,d], [f,g,a]], [a,e], Outlist).
------------in common--------------
L is:
[a,e]
H is:
[a,b,c]
Out2list is:
[a]
------------in common--------------
L is:
[a,e]
H is:
[e,b,d]
Out2list is:
[e]
------------in common--------------
L is:
[a,e]
H is:
[f,g,a]
Out2list is:
[a]
true.
首先,让我们观察一下您已经写了一个谓词common / 2和一个谓词common / 3。阅读您的问题,我想您打算将前者作为common / 3的基本案例。考虑要描述的关系,定义空列表和任何其他列表的交集为空列表将是有意义的:
common([],_,[]).
但是,尚不完全清楚您期望第三个参数是什么。在您的问题中,您写道它应该是常见项目的数量。在谓词common / 3中使用length / 2支持这种解释。在这种情况下,您希望在第三个列表中具有各个相交的长度:
common([],_,[]).
common([H|T], L, [Len|Out]):- % Len is in the 3rd list
intersection(H,L,I), % I is intersection of H and L
length(I,Len), % Len is length of I
common(T, L, Out). % the same for T, L and Out
使用此版本,您的示例查询将产生:
?- common([[a,b,c], [e,b,d], [f,g,a]],[a,e],I).
I = [1,1,1]
但是,在您的第一条评论中,您写道自己想要Outlist
成为[a]
。这表明您要在第三个参数中使用列表而不是数字。但是,查看您的示例查询[a]
并不能解决问题。一方面,如果您要查看第一个列表的元素与第二个参数的所有交集,则可能需要编写以下内容:
common2([],_,[]).
common2([H|T], L, [I|Out]):- % I is in the third list
intersection(H,L,I), % I is intersection of H and L
common2(T, L, Out). % the same for T, L and Out
这将产生您的示例:
?- common2([[a,b,c], [e,b,d], [f,g,a]],[a,e],I).
I = [[a],[e],[a]]
另一方面,如果您要查看第一个参数与第二个参数的所有列表的交集,则可能需要执行以下操作:
common3([],_,[]). % special case empty list
common3([H|T],L,I) :- % if 1st list not empty
common3_([H|T],L,I). % I is described in common3_/3
common3_([],I,I). % if the list is empty I = Outlist
common3_([H|T], L, O) :-
intersection(H,L,I), % I is intersection of H and L
common3_(T,I,O). % only the elements in I can be in O
在您的示例中列出了这种收益
?- common3([[a,b,c], [e,b,d], [f,g,a]],[a,e],I).
I = []
因为这三个列表都a
没有e
出现,也没有出现。但是,如果您添加a
到第二个列表:
?- common3([[a,b,c], [e,b,d,a], [f,g,a]],[a,e],I).
I = [a]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句