gen:equal+hash on hashes or other non-struct data structure

11 views
Skip to first unread message

David Storrs

unread,
Oct 1, 2019, 10:21:16 PM10/1/19
to Racket Users
Is it possible to put gen:equal+hash on something other than a struct?
For example, there's a hash, hasheqv, and hasheq. Is there a way to
have a hash with a user-provided key-comparison function?

Philip McGrath

unread,
Oct 1, 2019, 10:38:25 PM10/1/19
to David Storrs, Racket Users
On Tue, Oct 1, 2019 at 10:21 PM David Storrs <david....@gmail.com> wrote:
For example, there's a hash, hasheqv, and hasheq.  Is there a way to
have a hash with a user-provided key-comparison function?

You probably want `define-custom-hash-types` and the related functions: https://docs.racket-lang.org/reference/dicts.html#(form._((lib._racket%2Fdict..rkt)._define-custom-hash-types)) More generally, you can of course use `gen:dict` to do exactly what you want. There are corresponding options for sets, also.
 
Is it possible to put gen:equal+hash on something other than a struct?

In general, this would mean redefining how `equal?` works on built-in datatypes, which would cause trouble for libraries that use those types. You can choose what `equal?` means for datatypes you define, and you can choose to use some other notion of equality on datatypes you're comparing, but you can't mess with what `equal?` means when other people's code calls it on other people's datatypes.

One alternative that can sometimes make sense is creating a wrapper struct that basically is just there to hang methods like `gen:equal+hash` on.

-Philip
 

David Storrs

unread,
Oct 1, 2019, 11:06:27 PM10/1/19
to Philip McGrath, Racket Users
Perfect. Thank you, Philip.

The example definition is: (define-custom-hash-types string-hash
#:key? string? string=? string-length)

'string-length' in the above is the "optional hash function". What
does that mean? It's not demonstrated in the example code.
Reply all
Reply to author
Forward
0 new messages