I have two lists:
L1 = [[a,b,c], [e,b,d], [f,g,a]]
L2 = [a,e]
I want to compare L2 with each list in L1 and find the number of common items. I am trying following code:
common([],L).
common([H|T], L, Out):-
intersection(H,L,Out), common(T, L, Out),
length(Out,Len).
However, it is not working:
?- common([[a,b,c], [e,b,d], [f,g,a]], [a,e], Outlist).
false.
The main list remains list in list (as seen after debugging with writeln statements):
L is:
[a,e]
H|T is:
[[f,g,a]]
Outlist = [] .
Where is the problem and how can I correct this?
I edited the code to debug and found that somehow it has started working:
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.
outlist
? – Sergey Kalinichenko[[f,g,a]]
is a list of ONE ELEMENT, which is[f,g,a]
.[a,e]
is a list of TWO ELEMENTS, which area
ande
. Clearly, these two lists do not have an element in common since{f,g,a]
is not the same as eithera
ore
. Therefore,intersection([a,e], [[f,g,a]], R)
results inR = []
. So your original problem is that you have lists of lists that you are intersecting with flat lists.[[f,g,a]]
is a list of one element.[f,g,a]
is a list of 3 elements. – lurkercommon
. Do you just want it to succeed if it finds an intersection? That's all it currently does without thewriteln
statements. – lurker