Playing with Haskell’s typeclasses I created an instance of a typeclass of a list, whose elements are not an instance of that typeclass:
class Three a where
three :: a -> [a]
instance (Three a) => Three [a] where
three x = [x, x, x]
I get a different error message for a list of Integers and for a list of Chars:
Chars
*Main> three ['c']
<interactive>:11:1:
No instance for (Three Char)
arising from a use of `three'
Possible fix: add an instance declaration for (Three Char)
In the expression: three ['c']
In an equation for `it': it = three ['c']
Integers
*Main> three [1, 2]
<interactive>:12:8:
Ambiguous type variable `t0' in the constraints:
(Num t0) arising from the literal `1' at <interactive>:12:8
(Three t0) arising from a use of `three' at <interactive>:12:1-5
Probable fix: add a type signature that fixes these type variable(s)
In the expression: 1
In the first argument of `three', namely `[1, 2]'
In the expression: three [1, 2]
Why??
(Now, the error for Chars is understood – there is no instance for it. But the ambiguity error for Integers is not clear to me. I thought that maybe that’t because integers are already an instance of something (Num) so I created another arbitrary typeclass and an instance of it for Char, but got the same error for Char as before).
I’ll appreciate your help
The first error points out that there is no instance for
ThreeforChar. As you say, easy!However, in the second case, since the type of your numeric literals is unknown/polymorphic, GHC can’t tell if there is an instance for them or not. Hence, the error isn’t about a missing instance, but an ambiguous variable.
You could, for example, have valid instances for
Threefor bothIntandDouble. How would GHC know which to pick?(ignoring extended defaulting, that is).
So the error is different, because the type of error actually is different.