Haskell 正在声明 Show class 的一个实例
Haskell declaring an instance of Show class
我正在尝试围绕 类 和 Haskell 中的数据结构进行思考,特别是声明它的类型实例。我可以让它与一些 类 和数据类型一起工作,但不是所有的,所以我一定遗漏了一些东西。具体来说,我有以下数据声明:
data LinkedList a = End | Link a (LinkedList a)
我想为该类型声明一个 Show 实例,以便输出看起来接近 "el1, el2, el3, el4, ..."
instance Show LinkedList where
show (End) = "."
show (Link a b) = show a ++ "," ++ show b
不出所料,这不起作用...知道为什么吗?我想我理解 "data" 和 "type" 的意思,但我不确定我是否对 类 和实例感到满意。谢谢
instance Show LinkedList where
LinkedList
不是类型,LinkedList a
是类型。更正这一点,我们得到
instance Show (LinkedList a) where
然后,我们得到另一个错误,因为我们对 a
类型的值调用 show
。我们需要要求 a
也属于 class Show
。
instance Show a => Show (LinkedList a) where
现在应该可以了。
我正在尝试围绕 类 和 Haskell 中的数据结构进行思考,特别是声明它的类型实例。我可以让它与一些 类 和数据类型一起工作,但不是所有的,所以我一定遗漏了一些东西。具体来说,我有以下数据声明:
data LinkedList a = End | Link a (LinkedList a)
我想为该类型声明一个 Show 实例,以便输出看起来接近 "el1, el2, el3, el4, ..."
instance Show LinkedList where
show (End) = "."
show (Link a b) = show a ++ "," ++ show b
不出所料,这不起作用...知道为什么吗?我想我理解 "data" 和 "type" 的意思,但我不确定我是否对 类 和实例感到满意。谢谢
instance Show LinkedList where
LinkedList
不是类型,LinkedList a
是类型。更正这一点,我们得到
instance Show (LinkedList a) where
然后,我们得到另一个错误,因为我们对 a
类型的值调用 show
。我们需要要求 a
也属于 class Show
。
instance Show a => Show (LinkedList a) where
现在应该可以了。