Intersection and union of 2 lists

后端 未结 7 1838
青春惊慌失措
青春惊慌失措 2020-11-27 07:41

i\'m starting up learning prolog (i use SWI-prolog) and i did a simple exercise in which i have 2 lists and i want to calculate their intersection and union. Here is my code

7条回答
  •  北海茫月
    2020-11-27 08:14

    % Element X is in list?

    pert(X, [ X | _ ]).

    pert(X, [ _ | L ]):- pert(X, L).

    % Union of two list

    union([ ], L, L).

    union([ X | L1 ], L2, [ X | L3 ]):- \+pert(X, L2), union(L1, L2, L3).

    union([ _ | L1 ], L2, L3):- union(L1, L2, L3).

    % Intersection of two list

    inter([ ], _, [ ]).

    inter([ X | L1 ], L2, [ X | L3 ]):- pert(X, L2), inter(L1, L2, L3).

    inter([ _ | L1 ], L2, L3):- inter(L1, L2, L3).

提交回复
热议问题