In: Computer Science
Please explain this prolog code line by line.
union([X|Y],Z,W) :- member(X,Z), union(Y,Z,W).
union([X|Y],Z,[X|W]) :- \+ member(X,Z), union(Y,Z,W).
union([],Z,Z).
Code1 - union([X|Y],Z,W) :- member(X,Z), union(Y,Z,W)
Explainaton - [X|Y] is simply a list with head(first element) is X and tail( all the other elements) is Y.
union(L1,L2,L) denotes the union of L1 and L2 producing the output L. As example union([1,2,3,4],[1,a,b,4],A) will produce the output A = [2,3,1,a,b,4].
Now the code union([X|Y],Z,W) :- member(X,Z), union(Y,Z,W) will perform a union of a list with head X and tail Y with list Z and the output will be W.Now if X is already a member of list Z " member(X,Z) " , then there is no need to include X in the union. Hence, union(Y,Z,W) union of list Y with Z giving the output W.
Code2 - union([X|Y],Z,[X|W]) :- \+ member(X,Z), union(Y,Z,W)
Explainaton - code union([X|Y],Z,[X|W]) :- \+ member(X,Z), union(Y,Z,W) will perform a union of a list with head X and tail Y with list Z and the output will be list W with head X. " \+ " means not , \+ member(X,Z) means X is not the member of Z list , then X will also be included in the union, Thats's why X is head of output list W. Hence, union(Y,Z,W), union of Y with Z giving the output W whose head is X.
Code3 - union([],Z,Z)
Explaination - After taking all the elements(Head and tail elements) from [X|Y] it has become void. Hence, union([],Z,Z) union of the empty list with Z will return an output of Z.
Please let me know if you have any other doubts, and if you like the answer a thumbs up would be nice.