Simple maps/sets: parameterize the comparator?

Axel Rauschmayer axel at
Thu Dec 29 07:22:30 PST 2011

I’m not sure that there is much one can do to protect programmers from themselves, given that writing good hash functions is hard. One could provide a test suite.

Random thoughts:

- Enforce that both equality and hash function are specified. A common Java problem.

- Provide a hash function to complement – Brandon suggested Object.hash().

- Most common case: two objects are considered equal if (e.g.) two of their properties are equal. How can we help programmers here? Combining equals seems easy, combining hashes harder:

    function hashPerson(p) {
        return Object.combineHash(Object.hash(p.last), Object.hash(p.first));
        // Alternative: Object.hash(p.last, p.first)

    function equalsPerson(p1, p2) {
        return, p2.last) &&, p2.first)

- Internationalization mainly seems to matter for sorting, so it’s probably not an issue here.

On Dec 27, 2011, at 19:20 , Mark S. Miller wrote:

> Hi Axel, yes, I would like to extend their constructor in this way. However, I'm not sure how to spec it -- help appreciated. The problem is that the comparator needs to provide both an equivalence operation and a corresponding hash operation. When these agree, all is well. What should we specify happens when passing in a misbehaving comparator? The dilemma is that 
> 1) detecting misbehavior is expensive,  
> 2) having a deterministic collection misbehavior in the face of comparator misbehavior seems hard, and
> 3) we'd like to avoid yet more under-specification. The similar under-specification of Array.prototype.sort is already bad enough.
> On Tue, Dec 27, 2011 at 7:22 AM, Axel Rauschmayer <axel at> wrote:
> Currently, using is hard-coded. But one could allow a comparator function being handed in (with being the default).

Dr. Axel Rauschmayer
axel at


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list