如果您查看派生的输出,-ddump-deriv
您会发现每个数据族实例声明都产生了相同的instance Typeable1 DF
.
data family DF a
data instance DF Int = DFInt deriving (Typeable)
data instance DF Char = DFChar deriving (Typeable)
给
instance Data.Typeable.Internal.Typeable1 Main.DF where
Data.Typeable.Internal.typeOf1 _
= Data.Typeable.Internal.mkTyConApp
(Data.Typeable.Internal.mkTyCon
17188516606402618172## 4748486123618388125## "main" "Main" "DF")
[]
instance Data.Typeable.Internal.Typeable1 Main.DF where
Data.Typeable.Internal.typeOf1 _
= Data.Typeable.Internal.mkTyConApp
(Data.Typeable.Internal.mkTyCon
17188516606402618172## 4748486123618388125## "main" "Main" "DF")
[]
所以这种类型的派生并没有真正做你想做的事——它把族派生为Typeable1
不是实例。但是,很可能你需要instance (Typeable1 s, Typeable a) => Typeable (s a)
的是内置的。
data family DF a
deriving instance Typeable1 DF
data instance DF Int = DFInt deriving (Show)
data instance DF Char = DFChar deriving (Show)
data DFAll = forall a . Typeable a => DFAll (DF a)
toDFA :: Typeable a => DF a -> DFAll
toDFA = DFAll
fromDFA :: Typeable a => DFAll -> Maybe (DF a)
fromDFA (DFAll x) = cast x
和
*Main> fromDFA (toDFA DFInt) :: Maybe (DF Int)
Just DFInt