In said:
Pass the lists to the "intersection" function below.
This returns names/codes common to both.
http://www.gregorytoomey.com/index.php?option=content&task=view&id=9&Itemid=28
Hi, Greg. First, a typo (or two) in your page:
Example: Return the elements that occur more than once:
* duplicate(['apple','banana', 'pear', 'banana'])
Example: Return the elements that occur only once:
* duplicate(['apple','banana', 'pear', 'banana', 'apple'])
The "duplicate" is duplicated. I think you wanted the second one
to be "unique" (it's the only function defined on that page that
does not correspond to an Example). Also (and assuming you indeed
intended the second example above to refer to "unique"), the wording
of your description is ambiguous. My first reading was that
unique(['apple','banana', 'pear', 'banana', 'apple'])
would return ('pear') (the only element that occurs exactly once
in the input list, whereas, looking at the code I see that it would
return ('apple', 'banana', 'pear').
Also, a couple of suggestions. A set theorist would say that union
and intersection can take any number of arguments (including zero
or uncountably many!). That's hard to implement in Perl, but at
least one could generalize your functions to handle @_ arrays of
any size (including zero). Also, since you're implementing sets
as array refs, shouldn't union and intersection return array refs
as well?
# UNTESTED
sub union {
die "union: bad args\n" if grep defined $_ && ref $_ ne 'ARRAY', @_;
# return undef (= "the universe") if one of the arguments
# is undef
return undef if grep !defined, @_;
my %hash = map +($_ => 1), map @$_, @_;
[ keys %hash ];
}
sub intersection {
die "intersection: bad args\n" if grep defined $_ && ref $_ ne 'ARRAY', @_;
# the line below is so that we ignore any element in @_ that
# is the universe, since it does not affect the intersection
my @args = grep $_, @_;
# return undef (= "the universe") if @_ is empty
return undef unless @args;
my %hash;
++$hash{$_} for map @$_, @args;
[ grep $hash{$_} == @_, keys %hash ];
}
jill