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
We use the deriving strategies extension to be explicit about which deriving mechanism is in use for each typeclass.
Data.Hashable module comes from the
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.
In the REPL, we’ll demonstrate by showing the hash of the colors red and green.