我在创建打印树内容的函数时遇到了一些麻烦。我对数据类型Tree的定义如下:
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))
将文件加载到Hugs时,我收到以下错误:
ERROR file:.\Tree.hs:30 - Cannot justify constraints in explicitly typed binding
*** Expression : printTreeAux
*** Type : Tree a -> Int -> String
*** Given context : ()
*** Constraints : Show a
我已经搜索了一些澄清但发现没有什么可以真正帮助... 提前谢谢。
答案 0 :(得分: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,就好了。