Haskell 中的推导是如何进行的?
Haskell 中的代数数据类型 (ADT) 可以自动成为某些类型类的实例(例如 Show
、Eq
)通过从它们派生。
data Maybe a = Nothing | Just a
deriving (Eq, Ord)
我的问题是,这个deriving
是如何工作的,即Haskell如何知道如何为派生ADT实现派生类型类的函数?
另外,为什么派生
仅限于某些类型类?为什么我不能编写自己的可以派生的类型类?
Algebraic Data Types (ADTs) in Haskell can automatically become instances of some typeclasses (like Show
, Eq
) by deriving from them.
data Maybe a = Nothing | Just a
deriving (Eq, Ord)
My question is, how does this deriving
work, i.e. how does Haskell know how to implement the functions of the derived typeclass for the deriving ADT?
Also, why is deriving
restricted to certain typeclasses only? Why can't I write my own typeclass which can be derived?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简短的回答是,魔法:-)。这就是说,自动派生被纳入 Haskell 规范中,每个编译器都可以选择以自己的方式实现它。然而,关于如何使其可扩展,还有很多工作要做。
Derive 是 Haskell 的一个工具,可让您编写自己的派生机制。
GHC 曾经提供一个名为 Generic 的可派生类型类扩展类,但很少使用,因为它有点弱。
现在已经删除了,并且正在努力集成新的通用派生机制,如本文所述:http://www.dreixel.net/research/pdf/gdmh.pdf
有关详细信息,请参阅:
The short answer is, magic :-). This is to say that automatic deriving is baked into the Haskell spec, and every compiler can choose to implement it in its own way. There's lots of work on how to make it extensible however.
Derive is a tool for Haskell to let you write your own deriving mechanisms.
GHC used to provide a derivable type class extension called Generic Classes, but it was rarely used, as it was somewhat weak.
That has now been taken out, and work is ongoing to integrate a new generic deriving mechanism as described in this paper: http://www.dreixel.net/research/pdf/gdmh.pdf
For more on this, see:
来自 Haskell 98 报告:
以下是如何派生这些类型类的说明: haskell.org/onlinereport/衍生.html#衍生-appendix" rel="noreferrer">http://www.haskell.org/onlinereport/衍生.html#衍生-appendix
From the Haskell 98 report:
Here's the description of how to derive these type classes: http://www.haskell.org/onlinereport/derived.html#derived-appendix
可以使用 Template Haskell 以与派生子句类似的方式生成实例声明。
以下示例无耻地从 Haskell Wiki 窃取:
It is possible to use Template Haskell to generate instance declarations in a similar way to deriving-clauses.
The following example is shamelessly stolen from the Haskell Wiki: