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
.
Is there some way to tell that all Persistent
entities are Typeable
without adding deriving (Typeable)
to every specific data
clause? 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. It's just a type. For example, one can add a Persistent
instance for Maybe Integer
.
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
". One cannot say data Maybe Integer deriving Typeable
or anything like that.
If you are absolutely sure that every Persistent
thing must be Typeable
, you may want to add a constraint to your Persistent
class:
class Typeable a => Persistent a where ...
This however doesn't help you in any way with automatic derivation of 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.