layout: post
title: objects as hash keys
-

{{ page.title }}

7 November 2011

what others do

Hash tables with complex keys – keys that are not strings. Ideally a hash should be able to store any object as key; well Python solves this problem by introducing tuples – read only sequences can be key to a hash; which results in the introduction of yet another entity. Perl does not bother with this problem – if you insert a Array as key, then it just casts its to scalar – takes the length of the array as key that is; not very intuitive either.

Entities that can be stored as keys to an array

the problem

what to do if a hash table is inserted as key, or indirectly, if a hash table is part of an array, that is inserted as key. The problem is how to compare different hash table instances effectively, and how to compute the hash value of a hash object as key.

it can be done

to compute the hash key;

How to sort an arbitrary set of values:

comparing two arrays

is it all really that bad?

First of all the problem is mitigated if each element of the hash collection stores the hash value of the key; in this case the key has to be compared only in cases when the hash value of the given key is identical with a hash value of the collection entry. Even then most chances are that the ordered sequence of keys must not be created.

Also the sorted sequence of keys will only be computed on demand.

Is all this worth the effort ?

In a way yes; otherwise arrays as hash keys may not hold hashes; also yet another mind bending restriction is avoided as a start;