Haskell:Algebric数据类型,其类型变量必须是typeclass的实例
我试图定义一个algebric类型:Haskell:Algebric数据类型,其类型变量必须是typeclass的实例,haskell,types,polymorphism,typeclass,Haskell,Types,Polymorphism,Typeclass,我试图定义一个algebric类型: data MyType t = MyType t 并将其作为Show的一个实例: instance Show (MyType t) where show (MyType x) = "MyType: " ++ (show x) GHC抱怨,因为它无法推断“Show(MyType t)”中的类型“t”实际上是Show的一个实例,这是(Show x)所需要的 我不知道在何处以及如何声明“t”为Show的实例?在t的类型上添加类型约束: instance S
data MyType t = MyType t
并将其作为Show的一个实例:
instance Show (MyType t) where
show (MyType x) = "MyType: " ++ (show x)
GHC抱怨,因为它无法推断“Show(MyType t)”中的类型“t”实际上是Show的一个实例,这是(Show x)所需要的
我不知道在何处以及如何声明“t”为Show的实例?在
t
的类型上添加类型约束:
instance Show t => Show (MyType t) where
show (MyType x) = "MyType: " ++ (show x)
你也可以:
data MyType t = MyType t
deriving Show
如果您想要常规的节目格式。另一种解决方案是使用GADT:
data MyType t where
MyType :: Show a => a -> MyType a