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]')並檢查這兩種類型是否兼容。他們不是。您可以修復您的需求,或者刪除它並使用推斷的類型,或修復您的實施。 –