如果我有如下所示的代数数据类型
\ndata BinaryTree a = Leaf \n | Node a (BinaryTree a ) (BinaryTree a)\n deriving (Eq,Ord)\nRun Code Online (Sandbox Code Playgroud)\n这里Leaf代表空,a是节点,另外两个参数是来自该节点的子树。
\n有没有一种方法可以指定参数 a 应该导出Show
我试图给出我自己的 Show for 实现BinaryTree,我一开始很简单,例如:
instance Show (BinaryTree a) where\n show Leaf = "x"\n show (Node node left right) = show node++ "\\n" ++ show left ++" "++show right\nRun Code Online (Sandbox Code Playgroud)\n但show node不起作用->No instance for (Show a) arising from a use of \xe2\x80\x98show\xe2\x80\x99
show node如果node的类型是类型类的成员,则只能使用Show。因此,您应该在声明的头部添加类型约束instance:
-- ↓ type constraint
instance Show a => Show (BinaryTree a) where
show Leaf = "x"
show (Node node left right) = show node ++ '\n' : show left ++ " "++show rightRun Code Online (Sandbox Code Playgroud)