[英]Haskell: typeclass deriving from other typeclass
Suppose I have a typeclass for entities being kept in database. 假设我有一个保存在数据库中的实体的类型类。 Some simplified example may look like this:
一些简化的示例可能看起来像这样:
class Persistent a where
fetch :: Int -> IO (Maybe a)
store :: a -> IO Bool
Now I found that for store
I may need to know the type of entity, so it should be also Typeable
. 现在,我发现对于
store
我可能需要了解实体的类型,因此它也应该是Typeable
。
Is there some way to tell that all Persistent
entities are Typeable
without adding deriving (Typeable)
to every specific data
clause? 是否有某种方法可以说明所有
Persistent
实体都是可Typeable
而无需在每个特定的data
子句中添加deriving (Typeable)
? Eg like this: 例如:
class Persistent a deriving (Typeable) where
fetch :: Int -> IO (Maybe a)
store :: a -> IO Bool
No, this is not possible. 不,这是不可能的。
In class Persistent a
, a doesn't have to represent a data type declaration. 在
class Persistent a
,a不必表示数据类型声明。 It's just a type. 这只是一种。 For example, one can add a
Persistent
instance for Maybe Integer
. 例如,可以为
Maybe Integer
添加一个Persistent
实例。
instance Persistent (Maybe Integer) where ...
So it doesn't make much sense to talk about "adding a deriving (Typeable)
clause to all a
s that happen to be Persistent
". 因此,它并没有太大的意义谈“添加
deriving (Typeable)
条款向所有a
碰巧为S Persistent
”。 One cannot say data Maybe Integer deriving Typeable
or anything like that. 不能说
data Maybe Integer deriving Typeable
或类似的东西。
If you are absolutely sure that every Persistent
thing must be Typeable
, you may want to add a constraint to your Persistent
class: 如果您完全确定每个
Persistent
事物都必须是Typeable
,则可以向Persistent
类添加约束 :
class Typeable a => Persistent a where ...
This however doesn't help you in any way with automatic derivation of Typeable
. 但是,这对
Typeable
自动派生没有任何帮助。 It just requires that for every Persistent
instance there should be a Typeable
instance, which you still have to produce yourself one way or another (eg by adding deriving (Typeable)
to all relevant data types). 它仅要求每个
Persistent
实例都应该有一个Typeable
实例,您仍然必须以一种或另一种方式来产生自己(例如,通过将deriving (Typeable)
添加到所有相关的数据类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.