[英]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.