2

The code successfully finds right intersection (runtime/debug, gtrace) but after there is no common elements(intersections) in either list it does some stuff and returns false. It has to return a list of intersections. How to fix it?

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.

Sample query with expected result and output:

?- int([1,3,5,2,4],[6,1,2],[]).
[1,2]                            % expected: output by side-effect
true.                            % expected: query succeeds
repeat
  • 18,496
  • 4
  • 54
  • 166
J.Olufsen
  • 13,415
  • 44
  • 120
  • 185
  • What does your TEST call return, and what are you expecting it to return? – Will Ness Oct 27 '13 at 16:22
  • 1
    without remove/3 definition, it's hard to answer... BTW, any sensible intersection/3 definition should return [1,2] on your sample – CapelliC Oct 27 '13 at 16:57
  • 1
    Your TEST is not properly posed. Leave the third argument as a free variable, so the intersection of lists can be returned. As stated your query asks if the intersection is empty, and a False return would be correct (since the intersection is not empty). – hardmath Oct 28 '13 at 01:18

1 Answers1

1

No need to write recursive code!

Simply use tfilter/3 and list_memberd_t/3 like so:

?- tfilter(list_memberd_t([1,3,5,2,4]),[6,1,2],Xs).
Xs = [1,2].                           % succeeds deterministically
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166