在 Haskell 中推导是如何工作的? [英] How does deriving work in Haskell?

查看:34
本文介绍了在 Haskell 中推导是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代数数据类型(ADT)可以自动成为某些typeclasse的实例(例如Show, Eq) 从它们派生.

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)

我的问题是,这个 deriving 是如何工作的,即 Haskell 如何知道如何为派生 ADT 实现派生类型类的功能?

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?

另外,为什么 deriving 仅限于某些类型类?为什么我不能自己写可以派生的类型类?

Also, why is deriving restricted to certain typeclasses only? Why can't I write my own typeclass which can be derived?

推荐答案

简短的回答是,神奇的 :-).这就是说,自动派生已经融入到 Haskell 规范中,每个编译器都可以选择以自己的方式实现它.然而,在如何使其可扩展方面有很多工作要做.

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 是 Haskell 的一个工具,可让您编写自己的派生机制.

Derive is a tool for Haskell to let you write your own deriving mechanisms.

GHC 用于提供称为 泛型类,但很少使用,因为它有点弱.现在已经取消了,并且正在进行工作以整合本文所述的新通用派生机制:http://www.dreixel.net/research/pdf/gdmh.pdf

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 中推导是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆