Prolog intersection of three lists

269 views Asked by At

please can give some of you advice about interception of three lists in Prolog?

I done interception of two lists:

prunik([], _, []).

prunik([H1|T1], L2, [H1|Res]) :-
    member(H1, L2),
    prunik(T1, L2, Res).

prunik([_|T1], L2, Res) :-
    prunik(T1, L2, Res).

And it works, when I put this question:

prunik([1,3,5,2,4], [6,1,2], X).

I try remake this for three lists, but I really dont know. Any advice, please?

1

There are 1 answers

0
Grzegorz Adam Kowalski On

Your code for intersecting two lists is a bit faulty, see the last 3 answers:

?- prunik([1,3,5,2,4], [6,1,2], X).
X = [1, 2] ;
X = [1] ;
X = [2] ;
X = [].

But if you would like to extend your code to work on three lists:

prunik([], _, _, []).

prunik([H1|T1], L2, L3, [H1|Res]) :-
    member(H1, L2),
    member(H1, L3),
    prunik(T1, L2, L3, Res).

prunik([_|T1], L2, L3, Res) :-
    prunik(T1, L2, L3, Res).

Sample input/output:

?- prunik([1,2,3], [3,2,4,5,6], [2,3,4], R).
R = [2, 3] ;
R = [2] ;
R = [3] ;
R = [].