2

代码成功地找到了正确的交集(运行时/调试,gtrace),但是在任何一个列表中都没有公共元素(交集)之后,它会做一些事情并返回 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
4

1 回答 1

1

无需编写递归代码!

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

?- tfilter(list_memberd_t([1,3,5,2,4]),[6,1,2],Xs).
Xs = [1,2].                           % succeeds deterministically
于 2015-08-06T15:30:50.880 回答