我想要一个函数来检查空列表并告诉列表的内容。
使用以下代码,我无法tell使用[].
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list has one element: " ++ show x
main = do
putStrLn (tell [])
Run Code Online (Sandbox Code Playgroud)
错误是
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
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?
问题是[]intell []没有说明该列表元素的类型。这很重要,因为对于非空列表,我们使用show x,并且showaDouble和 的Int是不同的。
您可以通过以下方式提供列表的类型:
main = putStrLn (tell ([] :: [Int]))Run Code Online (Sandbox Code Playgroud)
当然,您可以使用不同的类型,例如String、[Double]、[[Char]]等。
| 归档时间: |
|
| 查看次数: |
461 次 |
| 最近记录: |