我想有一个函数来检查空列表并告诉列表的内容。
下面的代码,我不能用[]
调用tell
函数
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list has one element: " ++ show x
main = do
putStrLn (tell [])
错误是
main.hs:8:12: error:
* Ambiguous type variable `a0' arising from a use of `tell'
prevents the constraint `(Show a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance Show Ordering -- Defined in `GHC.Show'
instance Show Integer -- Defined in `GHC.Show'
instance Show a => Show (Maybe a) -- Defined in `GHC.Show'
...plus 22 others
...plus 12 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the first argument of `putStrLn', namely `(tell [])'
In a stmt of a 'do' block: putStrLn (tell [])
In the expression: do putStrLn (tell [])
|
8 | putStrLn (tell [])
| ^^^^^^^
exit status 1
如何解决这个问题?
问题是tell []
中的[]
没有说明该列表中元素的类型。这一点很重要,因为对于非空列表,我们使用show x
,而Double
和Int
的show
是不同的。
您可以使用以下命令提供列表的类型:
main = putStrLn (tell ([]:: [Int]))
当然你可以使用不同的类型,如String
,[Double]
,[[Char]]
等。