[英]Is there any generic Hashable typeclass in Haskell? (a.k.a. “deriving (Hashable)”)
是否有人編寫了泛型函數,以便可以為自定義數據類型自動生成hash
函數(使用deriving
機制)? 有幾次,我寫了以下類型的樣板,
data LeafExpr = Var Name | Star deriving (Eq, Show)
instance Hashable LeafExpr where
hash (Var name) = 476743 * hash name
hash Star = 152857
這可以自動生成:基本思想是每當添加數據時,您乘以素數,例如使用列表,
hash (x:xs) = hash x + 193847 * hash xs
基本上,我想寫的是
data LeafExpr = ... deriving (Hashable)
感謝所有非常有幫助的回復,每個人。 當我有時間時,我會嘗試添加一個通用方法作為練習。 現在(也許sclv指的是什么?),我意識到我可以編寫稍好的代碼,
instance Hashable LeafExpr where
hash (Var name) = hash ("Leaf-Var", name)
hash Star = hash "Leaf-Star"
使用ghc, 乘以隨機素數比編輯1中的tupling好得多 。 與Data.HashTable的沖突從95%(非常糟糕)變為36%。 代碼在這里:[ http://pastebin.com/WD0Xp0T1 ] [ http://pastebin.com/Nd6cBy6G ]。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.