develooper Front page | perl.perl5.porters | Postings from September 2002

Re: Collections

Thread Previous | Thread Next
From:
Brian Ingerson
Date:
September 29, 2002 11:38
Subject:
Re: Collections
Message ID:
20020929113752.D32117@ttul.org
On 29/09/02 13:01 -0400, Michael G Schwern wrote:
> Can't just sit on our hands waiting for Perl 6 to arrive.  Gotta do
> something with all that free time.

I'm with Mike. Adding real support for complex keys to Perl5 would be a
fun research project. I've already spent a bunch of time thinking about
this because YAML has syntax support for serializing complex hash keys.
This is already in use in the Ruby and Python implementations. I was
going to look for a way to fake it in Perl using shadowing techniques.
But this magic would not run deep.

We have to consider the following issues:
  - mutability of SVs
  - indentity vs equality
  - hashing algorithm for deep structures

Just using a pointer address for hashing works fine for "identity", but
not for equality:

    $key = [1, 2, 3];
    $card{$key} = "the Queen of Hearts";
    $myhand = $card{[1, 2, 3]};      # equality issue!
    # What do i have in $myhand?
    push @$key, 4;
    $myotherhand = $card{$key};      # mutability issue!
    # What's in $myotherhand?

Ruby seems to solve this best. Since everything is an object, any object
supporting a hash() method can be used as a key. The hash key is cached
after the first call to hash(). ie It becomes basically immutable (as
far as hashing is concerned). The object can also support rehash() if
the user wants to force the cached value to be recalulated.

Since not everything is an object in Perl, we'd probably want support
special methods similar to DESTROY that could be attached to any SV.Any
SV with SVf_ROK that is used as a hash key could have a magic
psuedo-class (complex::keys) added to its referent. This class would
support the methods HASH() and REHASH(). Real (blessed) objects could
inherit from complex::keys or write their own hashing algorithm. I'm
just thinking out loud here.

Well, this should really be done as a pragma module. How about 'use
keys', or something. I'd be happy to get this started. I can do it in
conjunction with my Inline port to the core (which is coming along
well). I was telling Hugo that Inline needs a core module to build in
order for people to test and complete the various platform ports. I've
started with a simple one called Perl5API.pm, but keys.pm is another
possibility.

The upshot functionally is that with 'use keys' both hands would get the
Queen.

Cheers, Brian

PS See how I like to bring all my projects together ;)

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About