Car*_*ada 1 printing tree haskell
我以前从未在Stackoverflow中看到过这个具体问题,而其他问题对我没有帮助(我在打开此问题之前已经尝试过).
当我尝试以这种方式打印二进制树时:
data BinTree a = ET | Branch (BinTree a) a (BinTree a) deriving Show
ejC:: BinTree a -> String
ejC ET = ""
ejC (Branch x y z) = (ejC x) ++ "|-" ++ y ++ "-|" ++ (ejC z)
Run Code Online (Sandbox Code Playgroud)
该模块给出了这个错误:
Couldn't match expected type `[Char]' with actual type `a'
`a' is a rigid type variable bound by
the type signature for ejC :: BinTree a -> String at Types2.hs:24:7
Relevant bindings include
z :: BinTree a (bound at Types2.hs:26:17)
y :: a (bound at Types2.hs:26:15)
x :: BinTree a (bound at Types2.hs:26:13)
ejC :: BinTree a -> String (bound at Types2.hs:25:1)
In the first argument of `(++)', namely `y'
In the second argument of `(++)', namely `y ++ "-|" ++ (ejC z)'
Run Code Online (Sandbox Code Playgroud)
谢谢你们.
GHC在这里告诉你很多.好像在说些什么y,对吧?而且(++)呢?那么,那些东西有哪些类型?
y :: a
(++) :: [t] -> [t] -> [t]
Run Code Online (Sandbox Code Playgroud)
好吧,因为它y是一个参数,(++)它必须是与它a相同类型的情况[t].因为("-|" ++ (ejC z)),String是另一个参数(++),该类型必须是String:
a ~ [t] ~ String
Run Code Online (Sandbox Code Playgroud)
但是你的类型签名说它适用于任何类型a,而不仅仅是String.因此错误.
您可以通过几种方式解决这个问题.您可以更改类型签名以限制a为String:
ejC:: BinTree String -> String
ejC = -- ...
Run Code Online (Sandbox Code Playgroud)
它不适用于任何类型的树,只是字符串树,但也许这就是你想要的.
或者,您可以尝试以a某种方式将树中的值转换为字符串.有一种常见的方法可以将一个东西变成一个String,这是通过使用该show函数,但它要求该类型具有Show的实例.因此,将该约束添加到函数签名中,并调用show函数体:
ejC:: Show a => BinTree a -> String
ejC ET = ""
ejC (Branch x y z) = (ejC x) ++ "|-" ++ show y ++ "-|" ++ (ejC z)
Run Code Online (Sandbox Code Playgroud)