mayor ::[Integer] -> Integer -> Maybe Int
mayor [] _ = 0
mayor (x:xs) y = if x > y then findIndex (==x) (x:xs) else mayor xs y
為什么我會收到錯誤“定義市長所需的 Num (Maybe Int) 實體”
uj5u.com熱心網友回復:
在您使用文字的第二行0,您可能希望它具有 type Int。如果您將其添加為型別簽名,您將收到更多資訊錯誤:
mayor ::[Integer] -> Integer -> Maybe Int
mayor [] _ = 0 :: Int
mayor (x:xs) y = if x > y then findIndex (==x) (x:xs) else mayor xs y
B.hs:3:14: error:
? Couldn't match expected type ‘Maybe Int’ with actual type ‘Int’
? In the expression: 0 :: Int
In an equation for ‘mayor’: mayor [] _ = 0 :: Int
|
3 | mayor [] _ = 0 :: Int
| ^^^^^^^^
現在您可以看到您的函式的型別簽名指定它將回傳一個 type 值Maybe Int,但在您的代碼中您回傳一個 type 值Int。
您可以通過包裝0在Just包裝器中解決此問題:
mayor ::[Integer] -> Integer -> Maybe Int
mayor [] _ = Just 0
mayor (x:xs) y = if x > y then findIndex (==x) (x:xs) else mayor xs y
這將修復錯誤,但我認為這不會滿足您的期望(提示:findIndex (== x) (x:xs)將始終回傳Just 0)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326050.html
標籤:哈斯克尔
