Gregory said:
Those are good if you have sets in arrays.
But if you have to store sets in Perl then arrays are not the natural type.
The natural type in Perl is the valueless hash (i.e. one with only keys).
Some what one usually thinks of as the primative set operations are not
primative in this implementation but the primatives you do have are
sufficient.
The primatives you get are:
Add a list of elements to set:
@set{'element1','emement2'} = ();
Remove a list of elements from set:
delete @set{'element1','emement2'};
Enumerate elements of set:
my
@elements = keys %set;
Test if one element is in a set:
exists $set{$element};
Reduce a list to those elements in a set (also test if ant of a list is
in the set in a scalar context):
grep { exists $set{$_} } LIST;
(Note for large data there is an unpleasant overhead for using grep in a
scalar context so for large data don't - roll your own loop).
Union is not as often wanted as you may think - most of the time people
think they want union they can really make do with "add a list elements
to a set".
my %union = ( %set1, %set2 );
Intersection is non-primative but is not as often wanted as you may
think - most of the time people think they want intersection they can
really make do with "reduce a list to those elements in a set".
my %intersection;
@intersection{ grep { exists $set1{$_} keys %set2 }} = ();