自动获得节目实例假设我有一个复杂GADT与许多隐藏类型参数的构造函数:为GADTs
data T where
A :: Num n => n -> T
B :: (Num n, Integral m) => n -> m -> T
C :: Floating a => [a] -> T
-- and so on
Z :: Num n => n -> n -> T
我想使这个数据类型showable,而无需手动编写的实例。问题是,由于Show
不再是Num
的超类,因此编译器只需添加一个简单的deriving instance Show T
即可推断它必须将Show
约束添加到所有内部隐藏类型参数中。
对于每个隐藏类型参数时,它输出像
Could not deduce (Show n) arising from a use of 'showsPrec'
from the context Num n
bound by a pattern with constructor
A :: forall n. Num n => n -> T
...
Possible fix:
add (Show n) to the context of the data constructor 'A'
添加Show
约束到数据类型是不是一种选择,因为相关它限制了T
可能居民。好像deriving instanec Show T
应该在隐藏的数据类型上引入约束Show
,虽然我不确定。
我该怎么办?
如果增加约束将限制居民,导出机制当然不会为你做,也不希望它。 – Lazersmoke
@Lazersmoke我的意思是将约束添加到派生实例。这并不限制居民,它只是以一种连贯的方式构建“Show”实例。 – ThreeFx
没有好的T的Show实例,不管你做什么,除非你将所有Tyvars(包括存在)限制在Show中。 – Lazersmoke