2016-11-16 48 views
0

的情況下,會觸發以下錯誤:運行debugFunction getDebugTree「無法找到‘秀’功能」的錯誤時,參數顯示

data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Eq, Show) 

getDebugTree :: Tree Int 
getDebugTree = (Node 1 (Empty) (Node 2 Empty Empty)) 

debugFunction :: Show a => a -> Tree a -> Bool 
debugFunction _ _ = True 

ERROR - Cannot find "show" function for: 
*** Expression : debugFunction getDebugTree 
*** Of type : Tree (Tree Int) -> Bool 

我讀過

reverse []

ERROR: Cannot find "show" function for: * expression : reverse [] * of type : [a]

The top-level system for Hugs can only print values which belong to a type which can be shown, that is a type which belongs to the Show class. Now, the list type is an instance of Show, so what is wrong with reverse [] (which evaluates to [])? The problem is that the type of [] is polymorphic: [] :: [a] for all a. Not knowing a Hugs refuses to print a value of type [a]. Note that this behaviour applies to all polymorphic values. Given the definition

data Tree a = Empty | Node (Tree a) a (Tree a)

we have, on evaluating

Empty

the error message

ERROR: Cannot find "show" function for: * expression : Empty * of type : Tree a

Functions can be shown, but not very helpfully; printing any function results in

<< function>>

據我瞭解擁抱不知道,因此拒絕打印(即使我打印布爾?)所以我試圖讓它成爲Show的一個實例,但它仍然無效,這裏有什麼問題?

回答

3

看那debugFunction類型。

debugFunction :: Show a => a -> Tree a -> Bool 

debugFunction需要兩個參數,所述第二部分是一個Tree a。你只能通過一個。類型檢查器看到您傳遞Tree Int作爲第一個參數,並推斷出a ~ Tree Int。所以debugFunction getDebugTree功能等待Tree (Tree Int)類型的第二個參數。

debugFunction getDebugTree :: Tree (Tree Int) -> Bool 

我懷疑你打算使用getDebugTree作爲第二個參數debugFunction,這意味着你需要拿出一個Int作爲第一個使用。

debugFunction 0 getDebugTree :: Bool 

有關缺少的Show實例的錯誤消息來自REPL本身。它試圖打印出debugFunction getDebugTree的結果,但它不能顯示函數。

+0

啊謝謝你,我還是習慣哈斯克爾 – Aeron

+1

@Aeron GHCI通常會產生更好的錯誤 - 擁抱不再發展,而GHC是。事實上,GHCi錯誤包含一個可能的原因:「(也許你沒有應用足夠的參數函數?)」 – chi

相關問題