如何编写一个可导出的类? [英] how to write a derivable class?
问题描述
data Something = Something Integer派生(MyClass,Show)
class MyClass a where
hello :: MyClass a => a - > a
实例MyClass Integer其中
hello i = i + 1
main = print。 hello $ Something 3
但MyClass不可推导。为什么?
GHC不能神奇地为任意数据类型派生实例。但是,
可以利用这样的事实: newtype
声明为
相同的基础类型创建一个新名称,以便为那些使用
GeneralizedNewtypeDeriving
扩展名。所以,你可以这样做:
{ - #LANGUAGE GeneralizedNewtypeDivingiving# - }
newtype Something = Something Integer派生(MyClass,Show)
class MyClass a where
hello :: MyClass a => a - > a
实例MyClass Integer其中
hello i = i + 1
main = print。 hello $ Something 3
GHC无法派生新实例的原因是它不知道实例是什么
应该是。即使您的数据类型只有一个字段,它可能不一定是与该字段相同的
。能够为 newtype
s派生实例是很方便的,因为
通常用于为某些类型类提供不同的行为,或者用作
的一种方式类型系统用于分隔代码中具有相同类型但用途不同的内容。
i have this
data Something = Something Integer deriving (MyClass, Show)
class MyClass a where
hello :: MyClass a => a -> a
instance MyClass Integer where
hello i = i + 1
main = print . hello $ Something 3
but MyClass isn't derivable. Why?
GHC cannot magically derive instances for arbitrary data types. However, it
can make use of the fact that newtype
declarations create a new name for the
same underlying type to derive instances for those using the
GeneralizedNewtypeDeriving
extension. So, you could do something like this:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
newtype Something = Something Integer deriving (MyClass, Show)
class MyClass a where
hello :: MyClass a => a -> a
instance MyClass Integer where
hello i = i + 1
main = print . hello $ Something 3
The reason GHC cannot derive the new instance is that it does not know what the instance
should be. Even if your data type only has one field, it may not necessarily be the
same as that field. The ability to derive instances for newtype
s is convenient, since they
are usually used to provide different behaviours for certain typeclasses or as a way to
use the type system to separate things that have the same type but different uses in your code.
这篇关于如何编写一个可导出的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!