【发布时间】:2020-08-31 08:22:30
【问题描述】:
假设你有一个序列化器/反序列化器类型类
class SerDes a where
ser :: a -> ByteString
des :: ByteString -> a
事实证明,为每种类型 a 提供一个特殊的辅助函数至关重要,例如
compress :: ByteString -> ByteString -- actually varies with the original type
我将compress 视为一个函数,我想将它与每个a 关联,即SerDes。 (“关联”这个词可能是一个糟糕的选择,这也是互联网搜索没有结果的原因。)
这个例子并不像看起来那么做作,例如当decompress 是一个可选的
串行器/解串器的功能。 (是的,助手可以通过增加来避免
ser 带有控制压缩的开关 ser:: a -> Bool -> ByteString,或者更好地使用 Config 记录。但让我们坚持这个例子。)
这样做的一种方法是一个“虚拟”类,一个单例:
data For a = For
那么这将起作用:
class SerDes a where
ser :: a -> ByteString
des :: ByteString -> a
compress :: For a -> ByteString -> ByteString
compress 的 a 将被实例化为
compress (For :: For MyType) input = ...
另一种有点不寻常的方法是将所有功能都粘贴到记录中。
data SerDes a = SerDes { ser :: a -> ByteString
, des :: ByteString -> a
, compress :: ByteString -> ByteString
}
还有其他方法可以将compress 函数与a 类型“关联”吗?
【问题讨论】: