I have written this small function to retrieve the tail of a list:
let getTail l = if length l > 0 then tail l else "empty list"
Passing []to getTail returns empty list but passing [1,2,3] gives the following error:
<interactive>:1:14:
No instance for (Num Char)
arising from the literal `3'
Possible fix: add an instance declaration for (Num Char)
In the expression: 3
In the first argument of `getTail', namely `[1, 2, 3]'
In the expression: getTail [1, 2, 3]
I can’t understand what that error means. What is the problem? Using GHCi 7.0.4
Let’s think about the type of your
getTailfunction. Initially, we can imaginelto be any list. The return type, however, has to be aStringbecause you sometimes return"empty list". Since that’s part of an if statement where you might also returntail l, it meanslhas to be aString.So your
getTailfunction has typeString -> String.When you call
getTailwith[1,2,3], it expects aString, which is just a[Char]. Remember that numeric literals are overloaded:[1,2,3]is equivalent to calling[fromInteger 1, fromInteger 2, fromInteger 3]. So, given this list, Haskell is trying to get a number from aChar. SinceChars are not part of theNumclass, this fails, giving you your error.A good solution would be to return a
Maybetype and giveNothingfor the error rather than returning"empty list". So rewrite your function as:Now its type is
[a] -> Maybe [a]. Using this will force anybody using your function to check whethergetTailsucceeded before being able to use the result.Another option is to return
[]in place of “empty list”. In this case, yourgetTailfunction will work exactly likedrop 1.