Hashing

For a type to be used in a HashSet or as the key in a HashMap, the type must implement the hash method of the Hashable typeclass.

When you define a new datatype, you can get an automatically-generated hash function with the help of a few language extensions.

The default instance of Hashable uses generics.

Since the default Hashable instance does not require us to write any code at all, we can derive it with the anyclass strategy.

We use the deriving strategies extension to be explicit about which deriving mechanism is in use for each typeclass.

For this example, we’ll define a type called Color, with a byte (Word8) representing each of red, green, and blue.

Typeclasses with specific deriving support built into the compiler are called stock-derivable.

The presence of the Generic instance allows us to derive Hashable using the anyclass strategy.

In the REPL, we’ll demonstrate by showing the hash of the colors red and green.

It isn’t really important to us what the Int hash results are; all that matters is that it is improbable for two different values to give us the same hash.

Please note that this sort of hashing is different from secure cryptographic hashing.

Next: