intersect( [ ], X, [ ] ).
intersect( [ X|R ], Y, [ X|Z ] )
:–
mymember( X, Y ),
!, intersect( R, Y, Z ).
intersect( [ X|R ], Y, Z ) :– intersect( R, Y, Z ).
? – intersect( [ 0, 1, 6, 3 ], [
5, 1, 8, 2, 3, 9 ], X ).
X = [ 1, 3 ]
? – intersect ( [ 1 ], [ 4 ], X ).
X = [ ]
union( [ ], B, B ).
union( [H|R], B, U ) :–
mymember( H
, B ), !, union(R, B, U ).
union([H|R], B, [H|U ] ):–
union(R, B, U ).
Note: A precondition is B is a
list.
The following query succeeds.
?- union([],a,U).
but we don't consider "a" a set since it isn't a list. Therefore we
test that B is a list.
union( [ ], B, B) :- is_list(B).
? – union( [3, 7, 1, 6], [5, 7, 2,
4, 1], X ).
X = [3, 6, 5, 7, 2, 4, 1]
/*or some other order of elements
if rules are not written in the same order*/
? – union( [4], [1, 6, 8], X ).
X = [4, 1, 6, 8]