【发布时间】:2010-07-09 14:19:02
【问题描述】:
我有一个类型类MyClass,其中有一个函数可以生成String。我想用它来暗示Show 的一个实例,这样我就可以将实现MyClass 的类型传递给show。目前为止,
class MyClass a where
someFunc :: a -> a
myShow :: a -> String
instance MyClass a => Show a where
show a = myShow a
这给出了错误Constraint is no smaller than the instance head. 我也试过了,
class MyClass a where
someFunc :: a -> a
myShow :: a -> String
instance Show (MyClass a) where
show a = myShow a
这给出了错误,ClassMyClass' used as a type`。
如何在 Haskell 中正确表达这种关系? 谢谢。
我应该补充一点,我希望跟进 MyClass 的特定实例,这些实例会根据它们的类型发出特定的字符串。例如,
data Foo = Foo
data Bar = Bar
instance MyClass Foo where
myShow a = "foo"
instance MyClass Bar where
myShow a = "bar"
main = do
print Foo
print Bar
【问题讨论】:
-
仅供参考,我推荐了这个问题,因为它详细而简洁、清晰且格式良好。一个典型的问题,如果可能的话,我会再次推荐它。
标签: haskell