首页 > 解决方案 > 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

如何解决这个问题?

标签: functionhaskell

解决方案


问题是[]intell []没有说明该列表元素的类型。这很重要,因为对于非空列表,我们使用show x, 而showfor aDoubleInt是不同的。

您可以提供列表的类型:

main = putStrLn (tell ([] :: [Int]))

当然,您可以使用不同的类型,例如String, [Double],[[Char]]等。


推荐阅读