Reputation: 13
How does intersect(L1,L2,L3)
in second rule work? Can someone trace me through it? Still a beginner in Prolog.
intersect([],L,[]).
intersect([A|L1],L2,[A|L3]) :-
member(A,L2),
intersect(L1,L2,L3).
Upvotes: 1
Views: 91
Reputation: 372
The second rule means:
If the head of the first list is present in the second list,
then it is also present in the third.
Consider the lists L1 = [a, b, c]
and L2 = [d, b]
. We calculate their insection as follows:
intersect([a|[b,c]], L2, [a|L3]) :- member(a, L2), intersect([b,c], L2, L3)
a
is not in L2, so this is false. Proceeding:
intersect([b|[c]], L2, [b|L3]) :- member(b, L2), intersect([c], L2, L3)
b
is in L2
, so b
is in the intersection. Proceeding:
intersect([c|[]], L2, [c|L3]) :- member(c, L2), intersect([], L2, L3)
c
is not in L2
, so this is false. Proceeding:
intersect([], L2, [])
This is the base case. So the intersection is [b]
.
Upvotes: 2