Search code examples
prolog

How to find a common element in two lists? Prolog


Lets say I have two lists [1,2,3,4] and [2,4,5,1]. The common elements in these two lists are [1,2].

There is an easy approach for this question:

common_element(L1,L2) :- member(E,L1), member(E,L2).

But I am trying to write my own predicate:

common_element([],[]).   
common_element([H1|T1],[H2|T2]):-
        (   H1=H2-> writeln(H1),
        common_element(T1,[H2|T2]);  
        common_element([H1|T1],T2)).

But it isn't working. it is only checking for the first common element.

?- common_element([1,2,66,6],[5,6,3,1]).
1

It should return 1,6.


Solution

  • Based on Reema's answer, here's a more "useful" predicate that "returns" the common elements, instead of just writing them out and failing at the end.

    %common_element(L1, L2, CommonElements_Of_L1_and_L2)
    common_element([], _, []).
    common_element([H|T], L2, [H|L1]):- member(H, L2), !, common_element(T, L2, L1).
    common_element([_|T], L2,    L1):-  common_element(T, L2, L1).
    

    Example

    ?- common_element([1,2,66,6], [5,6,3,1], L).
    L = [1,6]