2014-12-04 53 views
1

我在創建一個函數來打印樹的內容時遇到了一些麻煩。我對數據類型定義樹爲:無法證明顯式鍵入的約束綁定錯誤 - 樹形打印

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show) 

打印樹的代碼是:

printTree :: Tree a -> String 
printTree (Node a left right) = printTreeAux (Node a left right) 0 

printTreeAux :: Tree a -> Int -> String 
printTreeAux EmptyTree _ = "" 
printTreeAux (Node a left right) depth = (replicate (6 * depth) ' ') ++ show a ++ "\n" ++ (printTreeAux left (depth + 1)) ++ "\n" ++ (printTreeAux right (depth + 1)) 

而且我得到加載文件時擁抱了以下錯誤:

ERROR file:.\Tree.hs:30 - Cannot justify constraints in explicitly typed binding 
*** Expression : printTreeAux 
*** Type   : Tree a -> Int -> String 
*** Given context :() 
*** Constraints : Show a 

我已經搜索了一些澄清,但沒有發現任何能真正幫助... 在此先感謝。

回答

3

變化:

printTree :: Tree a -> String 
printTree (Node a left right) = printTreeAux (Node a left right) 0 

到:

printTree :: Tree a -> String 
printTree x = printTreeAux x 0 

甚至更​​好:

printTree :: Tree a -> String 
printTree = (flip printTreeAux) 0 

有沒有必要模式匹配上printTree因爲你要轉發的參數printTreeAux。實際上,在您的模式匹配中,EmptyTree將永遠不會匹配printTree,因此會生成錯誤。

你還應該加上a約束,要求它的Show能,否則show a不會編譯:

printTree :: (Show a) => Tree a -> String 

和:

printTreeAux :: (Show a) => Tree a -> Int -> String 

由於you can see,這些修復,程序會編譯,並且run,就好了。

+0

它沒有工作,謝謝。 – user1898820 2014-12-04 20:51:59