function - Haskell 检查空列表
问题描述
我想要一个检查空列表并告诉列表内容的功能。
使用以下代码,我无法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
如何解决这个问题?
解决方案
问题是[]
intell []
没有说明该列表元素的类型。这很重要,因为对于非空列表,我们使用show x
, 而show
for aDouble
和Int
是不同的。
您可以提供列表的类型:
main = putStrLn (tell ([] :: [Int]))
当然,您可以使用不同的类型,例如String
, [Double]
,[[Char]]
等。
推荐阅读
- laravel - 调用未定义的方法 App\Product::link()
- javascript - $.weekline 不是 jquery 中的函数
- android - Android Kotlin:从目录中获取图像
- python - pyspark 操作没有扩大
- javascript - Angular Material Table 鼠标滚动时突出显示行
- ios - 移除渐变时渐变按钮崩溃
- r - 使用 map(v, reduce) 在 R 中创建斐波那契数列?
- php - GD Library doesn't work in PHP 7.4.6 on Windows
- flutter - Flutter:删除小部件之间的空间
- python - How to compare today's date and date stored in a string (without time)?