![]() |
|
Perl-Sensitive Sunglasses | |
PerlMonks |
Using a hash for an ordered set can make senseby stefp (Vicar) |
on Sep 23, 2001 at 03:58 UTC ( [id://114118]=perlmeditation: print w/replies, xml ) | Need Help?? |
Beginners are understimating the hashes utility if not ignoring their
mere existence. Exprimented users know when to choose an hash or an
array. I am trying here to formalize the choice process.
We have a set of elements. Should we shove it in an array or
a hash? If the set is unordered, it is clear that the choice
is to use a hash: If the set is ordered, it may be a stack or a queue; or a static list which elements are accessed by rank. In Perl all of those are stored in arrays. We don't have to remember fancy classes names here unlike the OO bondage languages. Now the interesting case... and less intuitive. The set has no duplicates and is ordered by some (possibly costly) function of the elements values and we are adding and supressing elements all the time. Because it is ordered, we are tempted to use an array; but insertion and deletion in a an array are complex and costly (splices), We may think of a linked list, but really the natural choice is usually the hash (or 2 hashes). Let's call val the ordering function.
We start by the case of one hash Adding an element: $hash{$elt}= val $elt
Because we have a one to one correspondance between keys and
values, we could use a an additional hash: a "reverse" hash
%rev. It has the property: $hash{$rev{$_}} == $_ == $rev{$hash{$_}} So if adding and deleting an element is really the rare case compared to iterating, than you are better using an array and the joice of splicing :( Sure enough, when we want to more operations than adding, deleting and iterating, richer data structures must be considered. This reflexion was triggered by On Removing Elements from Arrays Corrected to suppress the unneeded Schwartzian Transform as suggested below by merlyn below. The ordering function is already cached as value associated to key. The whole point of an ST is to avoid to recalculate that function over and over. The correction does not change the validity of the points made in that node. Thanks merlyn -- stefp
Back to
Meditations
|
|