develooper Front page | perl.perl6.language | Postings from February 2005

Re: Valid hash keys?

Thread Previous | Thread Next
Luke Palmer
February 27, 2005 14:35
Re: Valid hash keys?
Message ID:
Nigel Sandever writes:
> On Sun, 27 Feb 2005 02:20:59 -0700, (Luke Palmer) wrote:
> > I forgot an important concretity.  Hashes should compare based on the
> > generic "equal" operator, which knows how to compare apples and apples,
> > and oranges and oranges, and occasionally a red orange to an apple.
> > 
> > That is:
> > 
> >     3 equal 3              ==> true
> >     3 equal { codeblock }  ==> false
> >     3 equal "3"            ==> true
> > 
> I would have assumed a hash who shape was defined as C<Int> to perform
> the hashing function directly on the (nominally 32-bit) binary
> representation Int 2. 

I wasn't even thinking about implementation.  Sometimes it's good to let
implementation drive language, but I don't think it's appropriate here.

When we're talking about hashes of everything, there are a couple of
routes we can take.  We can go Java's way and define a .hash method on
every object.  We can go C++'s way and not hash at all, but instead
define a transitive ordering on every object.  We can go Perl's way and
find a string representation of the object and map the problem back to
string hashing, which we can do well.

But the biggest problem is that if the user overloads 'equal' on two
objects, the hash should consider them equal.  We could require that to
overload 'equal', you also have to overload .hash so that you've given
some thought to the thing.  The worry I have is that people will do:

    method hash() { 0 }

But I suppose that's okay.  That just punts the work off to 'equal',
albeit in linear time.

That may be the right way to go.  Use a Javaesque .hash method with a
sane default (an introspecting default, perhaps), and use a sane
equivalent default for 'equal'.  

As far as getting 2, 2.0, and "2" to hash to the same object, well, we
know they're 'equal', so we just need to know how to hash them the same
way.  In fact, I don't believe 2.0 can be represented as a Num.  At
least in Perl 5, it translates itself back to an int.  So we can just
stringify and hash for the scalar types.


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About