1

为了训练,我尝试创建与 Data.Tree 相同的数据结构:

data MyTree a = Tree a [MyTree a] 

但是当我尝试为此数据结构创建显示实例时遇到了麻烦:

instance Show (MyTree a) where
  show (Tree a [v]) = show a -- Only first element

我收到一个错误

No instance for (Show a)
arising from a use of `show'

这对我来说有些奇怪。正如我所看到的,功能显示能够与任何类型一起使用。

第二个问题:在标准库中使用了派生方法,但是有一些奇怪的定义:

instance Eq a => Eq (Tree a)
instance Read a => Read (Tree a)
instance Show a => Show (Tree a)
instance Data a => Data (Tree a)

这些是什么意思?

4

1 回答 1

5

Show可以为任何类型派生,但如果要使用派生版本,则必须让编译器知道。

为了使您的定义show (Tree a [v]) = show a起作用,a必须是Show. 它可以是派生实例,也可以是自定义实例。所以我们只需要告诉编译器这a是 的一个实例Show,就像这样。

instance (Show a) => Show (MyTree a) where
  show (Tree a [v]) = show a -- Only first element

诸如instance Eq a => Eq (Tree a)“只要a是 的实例Eq,则Tree a.

于 2013-09-05T14:23:16.347 回答