这里暧昧发生难度代码:类实例和哈斯克尔
data Tree t = NilT
| Node t (Tree t) (Tree t)
instance Show (Tree t) where
show NilT = ""
show Node t l r = (show t) ++ ", " ++ (show l) ++ ", " ++ (show r)
如何在“T秀”用“秀”使用默认设置,并使用“秀”与给出的定义的树数据我自己?
这里暧昧发生难度代码:类实例和哈斯克尔
data Tree t = NilT
| Node t (Tree t) (Tree t)
instance Show (Tree t) where
show NilT = ""
show Node t l r = (show t) ++ ", " ++ (show l) ++ ", " ++ (show r)
如何在“T秀”用“秀”使用默认设置,并使用“秀”与给出的定义的树数据我自己?
为了使用show t
,您必须将约束Show t
添加到您的实例定义中。
instance Show t => Show (Tree t) where
show NilT = ""
show (Node t l r) = show t ++ ", " ++ show l ++ ", " ++ show r
你也缺少括号在你的模式Node t l r
,和我删除周围的来电圆括号show
,因为它们是多余的,因为功能的应用程序已经具有最高优先级。
非常感谢! –
你也可能想看看'hlint',它为你做了一些括号固定的东西(等等)。 – MatrixFrog
只是旁注:有一个函数Data.List.intersperse
用于在列表元素之间放置一个值。
show (Node t l r) = concat $ intersperse ", " [show t, show l, show r]
可短,哈马尔指出:
show (Node t l r) = intercalate ", " [show t, show l, show r]
不幸的是,你可以不写map show [t, l, r]
,如列表中的元素需要有一个独特的类型。
这是一个功课题吗?它看起来可疑类似于最近的问题http://stackoverflow.com/questions/7478878/show-function-for-polymorphic-type和http://stackoverflow.com/questions/7479252/how-to-define-that- a-generic-type-is-printable – ivanm