1
我的树具有以下数据类型。遍历一个多态有限二叉树
data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving (Show)
我想打印使用左到右的深度优先遍历给定树的表示。
目前,我决定采用模式匹配。
showt :: Tree a -> [Char]
showt (Leaf a) = [a]
...
当我尝试使用GHCI运行它,这里的错误,我得到
• Couldn't match expected type ‘Char’ with actual type ‘a’
‘a’ is a rigid type variable bound by
the type signature for:
showt :: forall a. Tree a -> [Char]
at 2016.hs:31:10
• In the expression: a
In the expression: [a]
In an equation for ‘showt’: showt (Leaf a) = [a]
• Relevant bindings include
a :: a (bound at 2016.hs:32:14)
showt :: Tree a -> [Char] (bound at 2016.hs:32:1)
我不明白问题出在哪里得来的。 Haskell应该推断类型,不是?
'[A]'的类型为'[A]''同时需要showt'返回一个'[字符]'。你需要在'a'上添加'Show'约束,并使用'show'将值转换为字符串:'showt :: Show a => Tree a - > [Char]'。 – Lee
是的,Haskell推断类型。然后看看你所要求的类型(通过编写'showt :: Tree a - > [Char]')并检查这两种类型是否兼容。他们不是。您可以修复您的需求,或者删除它并使用推断的类型,或修复您的实施。 –