Hashing a primitive data type
This recipe demonstrates how to use a simple hash function on various primitive data types.
Getting ready
Install the
Data.Hashable
package from Cabal as follows:
$ cabal install hashable
How to do it…
Import the hashing function with the following line:
import Data.Hashable
Test the
hash
function on a string as follows; this function is actually a wrapper around thehashWithSalt
function with a default salt value:main = do print $ hash "foo"
Test out the
hashWithSalt
functions using different initial salt values as follows:print $ hashWithSalt 1 "foo" print $ hashWithSalt 2 "foo"
We can also hash tuples and lists as follows:
print $ hash [ (1 :: Int, "hello", True) , (0 :: Int, "goodbye", False) ]
Notice in the following output how the first three hashes produce different results even though their input is the same:
$ runhaskell Main.hs 7207853227093559468 367897294438771247 687941543139326482 6768682186886785615
How it works…
Hashing with a salt...