简体   繁体   English

Haskell中是否有任何通用的Hashable类型类? (a.k.a.“衍生(Hashable)”)

[英]Is there any generic Hashable typeclass in Haskell? (a.k.a. “deriving (Hashable)”)

Has anyone written a generic function so that hash functions can be generated automatically for custom data types (using the deriving mechanism)? 是否有人编写了泛型函数,以便可以为自定义数据类型自动生成hash函数(使用deriving机制)? A few times, I've written the following kind of boilerplate, 有几次,我写了以下类型的样板,

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

This could be generated automatically: the basic idea is that whenever adding data, you multiply by a prime, for example with lists, 这可以自动生成:基本思想是每当添加数据时,您乘以素数,例如使用列表,

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

Essentially, what I'd like to write is 基本上,我想写的是

data LeafExpr = ... deriving (Hashable)

Edit 1 编辑1

Thanks for all of the very helpful responses, everyone. 感谢所有非常有帮助的回复,每个人。 I'll try to add a generic method as an exercise when I have time. 当我有时间时,我会尝试添加一个通用方法作为练习。 For now (perhaps what sclv was referring to?), I realized I could write the slightly better code, 现在(也许sclv指的是什么?),我意识到我可以编写稍好的代码,

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

Edit 2 编辑2

Using ghc, multiplying by random primes works much better than tupling in edit 1 . 使用ghc, 乘以随机素数比编辑1中的tupling好得多 Conflicts with Data.HashTable went from something like 95% (very bad) to 36%. 与Data.HashTable的冲突从95%(非常糟糕)变为36%。 Code is here: [ http://pastebin.com/WD0Xp0T1 ] [ http://pastebin.com/Nd6cBy6G ]. 代码在这里:[ http://pastebin.com/WD0Xp0T1 ] [ http://pastebin.com/Nd6cBy6G ]。

How much speed do you need? 你需要多少速度? You could use one of the packages that use template haskell to generate serialization code to convert the value to binary and then hash the binary array with hashable . 您可以使用其中一个使用模板haskell的包来生成序列化代码,以将值转换为二进制,然后使用hashable对二进制数组进行哈希处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM