Home > other >  Haskell Check empty list
Haskell Check empty list

Time:09-22

I want to have a function which checks the empty list and tell the content of the list.
With following code, I can not call tell function with [].

tell :: (Show a) => [a] -> String  
tell [] = "The list is empty"  
tell (x:[]) = "The list has one element: "    show x  

main = do
 putStrLn (tell [])

The error is

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

How to fix this? Thanks a lot!

CodePudding user response:

The problem is that [] in tell [] does not say anything about the type of the elements of that list. This is important since for a non empty list, we use show x, and the show for a Double and Int are different.

You can provide the type of the list with:

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

Of course you can use a different type like String, [Double], [[Char]], etc.

  • Related