Dear monks,
recently I have found myself wanting to use sets, i.e. collections of unique values. I could use a CPAN package for it, but more often than not I simply write
my %set = (); my @new_items = ...; @set{@new_items} = (1) x @new_items;
Deleting items from the set is of course
delete @set{@other_items};
I don't know how common the idiom is. It may be inefficient with large sets and arrays, and the syntax is a bit peculiar for adding things to the set, but it saves conceptual effort and reduces running time compared to sorting and removing duplicate items later. You can also always reduce the set (hash) to an array with [keys %set].
Are there better ways to do it? Here, better can be any one of conceptually or syntactically clearer, less memory wasted in storing the items, or less memory wasted in adding items to the set.
A further advantage of the above idiom is that you can compute set difference and symmetric difference easily:
# Difference. sub difference { my %diff = %{ $_[0] }; delete @diff{ keys %{ $_[1] } }; \%diff; } # Symmetric difference. sub symmetric_difference { my %symm = (); my @set1 = keys %{ difference($_[0], $_[1]) }; my @set2 = keys %{ difference($_[1], $_[0]) }; @symm{@set1, @set2} = (1) x (@set1 + @set2); \%symm; }
An obvious problem with the idiom is auto-vivication, but as long as you're careful and consistent, it won't bite you.
--
print "Just Another Perl Adept\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Idiom: hashes as sets
by perrin (Chancellor) on Jul 02, 2008 at 18:39 UTC | |
by Narveson (Chaplain) on Jul 02, 2008 at 19:22 UTC | |
by parv (Parson) on Jul 04, 2008 at 02:38 UTC | |
by Anonymous Monk on Jul 03, 2008 at 14:22 UTC | |
by Anonymous Monk on Jul 03, 2008 at 14:57 UTC | |
|
Re: Idiom: hashes as sets
by dragonchild (Archbishop) on Jul 02, 2008 at 21:27 UTC | |
by Tanktalus (Canon) on Jul 03, 2008 at 16:00 UTC | |
by kyle (Abbot) on Jul 03, 2008 at 16:14 UTC | |
by vrk (Chaplain) on Jul 04, 2008 at 08:27 UTC | |
by Jenda (Abbot) on Jul 06, 2008 at 21:06 UTC | |
by dragonchild (Archbishop) on Jul 06, 2008 at 21:09 UTC | |
by Jenda (Abbot) on Jul 06, 2008 at 21:22 UTC | |
by dragonchild (Archbishop) on Jul 07, 2008 at 00:48 UTC | |
|
Re: Idiom: hashes as sets
by TGI (Parson) on Jul 03, 2008 at 01:30 UTC | |
|
Re: Idiom: hashes as sets
by locked_user sundialsvc4 (Abbot) on Jul 08, 2008 at 18:53 UTC |