Do hashkey and hashvalues give their results in the same order?
When working with hash tables in Racket, two useful functions are hashkeys
and hashvalues
. The first returns all the keys used in the hash table, as a list. The second returns, analogously, the values. Nothing terribly surprising there.
When we need to work, separately, with the keys and the values of a hash table, an interesting question presents itself:
Is it safe to assume that the list that hashkeys
returns has the same order as the list returned by hashvalues
?
Is, for instance, the first element of the list returned by hashvalues
the hash value of the first element returned by hashkeys
? To put the question in terms of code: is it true, for a hash table h
, that
1 2  (equal? (listref (hashvalues h) 0) (hashref h (listref (hashkeys h) 0))) 
and so forth, for 1, 2, etc.?
The answer is: No, that is not necessarily true.
If, in some cases, it is true, that’s accidental and not something to rely upon. The documentation for both functions says that the results are provided in an unspecified order
.
Think of it this way. When using hashkeys
and hashvalues
, you’re losing information. Applying these functions deliberately cuts the tie between the key and values of a hash. hashkey
gives just a list of keys; it makes no promises about the order of its results. And similarly for hashvalues
.
Demonstration
Here’s how you can convince yourself of this. Run the following code in DrRacket:
1 2 3 4 5 6 7 8 9 10 11 12 

These results show that you can’t really rely on the order. If you get results that don’t contradict the conjecture, consider yourself lucky.