Q about Lisp union
As I thought I understood it, Lisp union implements set union. So, I thought that
(union '(a a) '(a b))
would return (a b)
And, in fact, it does. This led me to think that (union '(a a) '(b))
would also return (A B)
However, it returns: (A A B)
Why does the fact that there is one less 'a in the second argument in the second call mean that there is one more 'a in the result? This is definitely not set-theoretic union. Why is the behavior of Lisp union defined this way?Here is the sequence of calls again:
[1]> (union '(a a) '(a b))
(A B)
[2]> (union '(a a) '(b))
(A A B)
7 comments
[ 4.3 ms ] story [ 25.9 ms ] thread... If either list-1 or list-2 has duplicate entries within it, the redundant entries might or might not appear in the result ...
there is an intersection between '(a a) and '(a b); the element 'a. Thus, the union would be the set of things inside the intersection --- 'a --- and the parts outside it --- 'b.
With the second union, there is no intersection, so the union is merely the set of things not in the intersection, which is the original sets, resulting in '(a a b). There is no relation defined in the union operation between those things not in the intersection, so they remain in the union set.
If I'm willing to accept '(a a) as representing the set '(a) when I use it as an input to union, I should be just as willing to accept '(a a b) as representing the set '(a b) when I receive it back from union.
The no-duplicates would seem to be a very important thing about union, and when they are removed or not. Union is just the complement of intersect, which would be the empty set for (a a) int. (b). So the union would be all the elements: (a a b) and after removing all duplicates you'd get (a b), which is exactly the behavior what you and I expect. Must be something with the duplicates rule.
So (union '(a b) '(a a)) gives (b a a).