我想有一個函式來檢查空串列并告訴串列的內容。 在下面的代碼中,我不能用[]呼叫tell函式。
tell :: (Show a) => [a] ->String
tell [] = "該串列為空"。
tell (x:[]) = "該串列有一個元素。" show x
main = do
putStrLn (tell [])
這個錯誤是
main.hs:8:12: error:
* Ambiguous type variable `a0' arising from a use of `tell'
阻止約束`(Show a0)' 被解決。
Probable修復:使用type注釋來指定`a0'應該是什么。
這些潛在的實體存在。
instance Show Ordering --定義在`GHC.Show'中
instance Show Integer --定義于`GHC.Show'。
instance Show a => Show (Maybe a) --在`GHC.Show'中定義的。 顯示'
...加上其他22個
...加上12個涉及范圍外型別的實體
(use -fprint-potential-物質 to see them all)
* In `putStrLn'的第一個引數,即`(tell [])
In一個'do'塊的陳述句:putStrLn (tell [])
In the expression: do putStrLn (tell [])
|
8 | putStrLn (tell [])
| ^^^^^^^
退出狀態1
如何解決這個問題?非常感謝!
uj5u.com熱心網友回復:
問題是[]在tell[]中沒有說任何關于該串列中元素的型別。這一點很重要,因為對于一個非空串列,我們使用show x,而對于Double和Int的show是不同的。
你可以用:
提供串列的型別。main = putStrLn (tell ([] :: [Int])
當然你可以使用不同的型別,如String、[Double]、[[Char]]等。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/329806.html
標籤:
