2017-03-15 103 views
1

我試圖構建一個功能打印二叉樹,所以我這樣做:我怎樣才能打電話給一個show instace打印一棵二叉樹?

instance Show a => Show (Tree a) where 
    show Null = "_" 
    show (Nod x e d) = "(" ++ show x ++ " " ++ show e ++ " " ++ show d ++ ")" 


left :: Tree a -> Tree a 
left (Nod x e d) = show e 

,但我收到此消息:

Couldn't match type `[Char]' with `Tree a' 
Expected type: Tree a 
    Actual type: String 
In the return type of a call of `show' 
In the expression: show e 
In an equation for `left': left (Nod x e d) = show e Failed, modules loaded: none. 
+0

提示:你的'left'函數的結果類型應該是什麼,你寫的類型簽名是怎麼說的? – duplode

+0

我試圖弄到樹的左側,所以我收到一棵樹,並返回另一棵樹的左側子樹 – Marcio

+1

如果您只想「left」返回左側子樹,則不需要使用「在其中顯示''show'產生一個'String'。 – duplode

回答

0

你的類型和值是不匹配的。你的函數left :: Tree a -> Tree a表示它返回一個Tree a,但函數體show e返回String(因爲show :: Show a => Tree a -> String)。

如果你想要一個將樹打印到標準輸出的函數,你需要有一個函數來執行IO和一個約束,以便樹的元素被認爲是Show的實例,所以它的類型需要是:left :: Show a => Tree a -> IO()和身體是:left (Nod x e d) = print eprint :: Show a => a -> IO()

如果你想要一個函數,一棵樹,然後返回它的左側爲String,則需要將函數的結果類型更改爲String ,並添加前面提到的Show約束:left :: Show a => Tree a -> String,並且正文將與您擁有的完全一樣。

如果你想要一個函數,一棵樹,然後返回它左側的樹,你應該讓你有型的簽名,但是從身體取出show(因爲你沒有轉化成a String):left (Nod x e d) = e