在 Haskell 中导出任意函数
在 Haskell 中使用派生实例时,是否可以派生任意类型的函数,或者我们仅限于特定的函数?
When working with derived instances in Haskell, is it possible to derive functions for arbitrary types, or are we restricted to particular functions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在 haskell 98 中派生以下类的实例:Eq、Ord、Enum、Ix、Bounded、Read 和 Show。
使用 ghc 扩展,您还可以派生以下类的实例:Typeable、Data、Functor、Foldable 和 Traversable。还有一个 ghc 扩展,允许新类型从其实现类型派生实例。
您无法派生任意类的实例,原因很简单,如果没有有关相关类的特殊知识,haskell 将不知道如何生成必要的函数。
You can derive instances of the following classes in haskell 98: Eq, Ord, Enum, Ix, Bounded, Read, and Show.
Using ghc extensions you can also derive instances of the following classes: Typeable, Data, Functor, Foldable and Traversable. There's also a ghc extension that allows a newtype to derive instances from its implementation type.
You can not derive instances of arbitrary classes for the simple reason that haskell would not know how to generate the necessary functions without special knowledge about the class in question.
就编译器知道如何为您派生的内容而言,您仅限于特定的类。如果您了解生成特定类型函数实现的一般方法,则可以使用预处理器或 Template Haskell 自己编写新的派生机制。
You are restricted to particular classes, in terms of what the compiler knows how to derive for you. Using a preprocessor, or Template Haskell, you can yourself code up new deriving mechanisms, if you know of general approaches to yielding implementations of functions for particular types.
另外两个答案是正确的。但如果您需要更多,hackage 上有一些软件包可以处理更多。我非常喜欢 Data.Derive ,因为您可以直接生成源代码(为了兼容性)或将其挂钩到 Template Haskell 中以在编译时执行此操作。已经支持了广泛的类,并且很容易添加对您自己的类的支持。摘要:为一个非常棒的图书馆做广告:-)
The other two answers are correct. But if you need more, there are some packages on hackage that can handle more. I like Data.Derive a lot, since you can generate the source code directly (for compatibility) or hook it into Template Haskell to do it at compile time. A wide range of classes are already supported, and it is very easy to add support for your own. Summary: advertising pitch for a damn fine library :-)
要补充 Don 的答案:为数据类型派生自定义功能称为通用编程 并且有很多文献与此相关。预处理器和 Template Haskell 并不是唯一的解决方案;请参阅概述论文之一,其中列出了其他选项的文献。
To add to Don's answer: deriving custom functionality for datatypes is called generic programming and there is a lot of literature about this. Preprocessors and Template Haskell are not the only solutions; see one of the overview papers that list of literature for other options.