1

在下面的代码中,我定义了一个代数数据类型,并且我(试图)使它成为 Show 的一个实例。但是,我收到编译时错误(包括在下面)。我究竟做错了什么?

我相信我使用了正确的语法(至少根据这篇文章)。对于上下文,我正在处理“99 Haskell 问题”中的问题 #13

data RepeatType a = Multiple (Int, a) | Single a

instance Show RepeatType where
  show (Multiple (n,x)) = "(" ++ n ++ " " ++ show x ++ ")"
  show (Single x)       = show x

我收到以下编译时错误:

test.hs:3:15:
    Expecting one more argument to `RepeatType'
    In the instance declaration for `Show RepeatType'
Failed, modules loaded: none.

例如,目标是让它在 GHCi 中按如下方式工作:

ghci> Multiple (5,'C')
(5 C)
ghci> Single 'D'
D

编辑:对不起,完全不相关的帖子标题 - 现在改变了。

4

1 回答 1

11

你的问题是它RepeatType本身并不是一个真正的类型,它是一个类型构造函数。Show只能为“正确”类型实例化,例如RepeatType a. 然而,要让它工作,你需要保证它a本身是 的一个实例Show,所以你最终会得到这样的东西:

instance (Show a) => Show (RepeatType a) where
  show (Multiple (n,x)) = "(" ++ show n ++ " " ++ show x ++ ")"
  show (Single x)       = show x

(注意:您还需要在定义的第一部分调用showon n,因为您不能连接 Ints 和 Strings。)

于 2014-10-21T17:13:29.507 回答