Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a unique Integer for each string?

Tags:

haskell

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.

like image 630
Andriy Drozdyuk Avatar asked Feb 22 '23 12:02

Andriy Drozdyuk


1 Answers

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.

like image 106
hammar Avatar answered Feb 24 '23 00:02

hammar