Is there a common hashable pattern in Haskell? (aka "getting (hashable)")

Has anyone written a generic function so that functions hashcan be generated automatically for custom data types (using a mechanism deriving)? Several times, I wrote the following type of template,

data LeafExpr = Var Name | Star deriving (Eq, Show)
instance Hashable LeafExpr where
    hash (Var name) = 476743 * hash name
    hash Star = 152857

This can be generated automatically: the main idea is that every time you add data, you multiply by a simple one, for example with lists,

hash (x:xs) = hash x + 193847 * hash xs

Essentially, I would like to write

data LeafExpr = ... deriving (Hashable)

Change 1

Thanks for all the very helpful answers, everyone. I will try to add a general method as an exercise when I have time. At the moment (maybe sclv had in mind?), I realized that I can write a little better code,

instance Hashable LeafExpr where
    hash (Var name) = hash ("Leaf-Var", name)
    hash Star = hash "Leaf-Star"

Edit 2

ghc, , tupling 1. Data.HashTable - 95% ( ) 36%. : [http://pastebin.com/WD0Xp0T1] [http://pastebin.com/Nd6cBy6G].

+5
1

? , haskell , - hashable.

+2

All Articles