這段代碼來自《Learn You a Haskell for Great Good!》一書:
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maximum' xs
它適用于非空串列,但提供一個空串列:
main = print $ maximum' []
給出這個編譯器錯誤:
由于使用“最大值”而產生的模棱兩可的型別變數“a0”會阻止解決約束“(Ord a0)”。
這是為什么?當提供一個空串列時,代碼不應該實際捕獲它嗎?我不明白錯誤資訊。
uj5u.com熱心網友回復:
由于使用“最大值”而產生的模棱兩可的型別變數“a0”會阻止解決約束“(Ord a0)”。
這意味著當您呼叫 時maximum' [],型別[]不明確:它可能是[Int]or[()]或其他東西。
在這種特殊情況下,結果恰好是相同的。編譯器在這里無法證明,一般情況下并非如此。考慮這個函式:
readAndPrepend :: (Read a, Show a) => String -> [a] -> String
readAndPrepend s xs = show (read s : xs)
如果你打電話readAndPrepend "42" [],結果應該是模棱兩可的:
ghci> readAndPrepend "42" ([] :: [Int])
"[42]"
ghci> readAndPrepend "42" ([] :: [Double])
"[42.0]"
ghci> readAndPrepend "42" ([] :: [()])
"[*** Exception: Prelude.read: no parse
ghci>
換句話說,a型別變數是“未解決的”,就像x數學方程中的自由。
您需要做的是選擇您希望串列成為的型別并明確指定它:
main = print $ maximum' ([] :: [()])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/486356.html
上一篇:比較兩個二叉搜索樹
