Eric Roode wrote:
> I wonder if it might not be a good idea to implement a function to
> compute the intersection of two sets-as-hashes.
>
> Intersection is the only basic set function that's not trivially
> implementable with perl hashes. Sure, it's not hard to do, with
> a loop and a small bit of programming, but maybe it should be a
> primitive.
Well, it's very easy to do... perhaps easier than you think.
@inter = grep { exists $set1{$_} } keys %set2;
But I still am not entirely comfortable with the notion that
sometimes you have think of the HASH VARIABLE as your set, and
sometimes the KEYS OF THAT HASH as your set.
If there were not this artificial distinction, we would be able
to write the quite natural set expression,
%inter = grep { exists $set1{$_} } %set2;
(which looks an awful lot like an ARRAY expression if you change
the %'s to @'s.) (And of course presuming grep() is smartened
up to do the right thing here.)
But we can't do that.
And if you wanted to do set difference, you could do it the easy way:
keys(%diff) = grep { ! exists $set1{$_} } keys %set2;
# assuming the semantics of keys(HASH) is changed
# appropriately.
or this way:
%diff = %set1;
delete @diff{ keys %set2 };
Why should I have to futz with "keys" in these situations?
Sets, in the mathematical sense, don't know from "keys".
This should work, if hashes were really sets:
%diff = grep { ! exists $set1{$_} } %set2;
%diff = %set1;
delete %diff{ %set2 };
or even
%diff -= %set2;
THAT's true set manipulation.
One possible source for hope in all this is Damian's proposed
"Pair" construction -- http://dev.perl.org/rfc/84.html
grep() would (or could) grep out a list of the PAIRs in a hash
which match the condition; and assigning such a list to a hash
would be well defined, and do the right thing.
--
John Porter
We're building the house of the future together.