如何指定 Haskell 中代数类型的参数类型

vij*_*icv 1 haskell

如果我有如下所示的代数数据类型

\n
data BinaryTree a = Leaf \n                    | Node a (BinaryTree a ) (BinaryTree a)\n                    deriving (Eq,Ord)\n
Run Code Online (Sandbox Code Playgroud)\n

这里Leaf代表空,a是节点,另外两个参数是来自该节点的子树。

\n

有没有一种方法可以指定参数 a 应该导出Show

\n

我试图给出我自己的 Show for 实现BinaryTree,我一开始很简单,例如:

\n
instance Show (BinaryTree a) where\n    show Leaf = "x"\n    show (Node node left right) =  show node++ "\\n" ++ show left ++"  "++show right\n
Run Code Online (Sandbox Code Playgroud)\n

show node不起作用->No instance for (Show a) arising from a use of \xe2\x80\x98show\xe2\x80\x99

\n

Wil*_*sem 8

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 right
Run Code Online (Sandbox Code Playgroud)