如何使用递归计算列表的交集?

时间:2013-10-27 13:16:02

标签: prolog

代码成功找到正确的交集(运行时/调试,gtrace),但在任一列表中没有共同元素(交叉点)后,它会执行一些 stuff 并返回false。它必须返回一个交叉点列表。如何解决?

remove(S,[S|T],L) :-
   remove(S,T,L),
   !.  
remove(S,[U|T],[U|L]) :-
   remove(S,T,L).
remove(_,[],[]).
remove(El,[El|List],List1) :-
   remove(El,List,List1).
remove(El,[El1|List],[El1|List1]) :-
   remove(El,List,List1).

l_inclusion(El,[]) :-
   fail.
l_inclusion(El,[El|_]).
l_inclusion(El,[El1|List]) :- 
   !,
   l_inclusion(El,List).

int(List1,List2,Result) :-
   l_inclusion(El,List1),
   l_inclusion(El,List2),
   remove(El,List1,NewList1),
   remove(El,List2,NewList2),
   int(NewList1,NewList2,[El|Result]),
   write(Result),
   nl.

带有预期结果和输出的示例查询:

?- int([1,3,5,2,4],[6,1,2],[]).
[1,2]                            % expected: output by side-effect
true.                            % expected: query succeeds

1 个答案:

答案 0 :(得分:1)

无需编写递归代码!

只需使用 tfilter/3list_memberd_t/3,就像这样:

?- tfilter(list_memberd_t([1,3,5,2,4]),[6,1,2],Xs).
Xs = [1,2].                           % succeeds deterministically