How can I hash a string in haskell to get a more-or-less unique hash value. For example:
hash:: String -> Integer
>hash "foo"
1234123412
>hash "bar"
5938454
Or something along those lines? I'm not familiar with hashing in haskell so any help would be appreciated! Thanks.
You can use the hashable package from Hackage. It provides hash functions for a number of standard types, including strings:
Prelude Data.Hashable> hash "foo"
653367
Prelude Data.Hashable> hash "bar"
649056
If you want to implement your own, hash functions are usually easy to express as a fold. For example, here's a variant of the DJB2 hash:
hash :: String -> Int
hash = foldl' (\h c -> 33*h `xor` fromEnum c) 5381
Note that these hash functions are meant to be simple and fast. If you're looking for more complex hash functions, you can find a selection in the cryptohash package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With