[Haskell-beginners] multi-parameter typeclass with default implementation
TP
paratribulations at free.fr
Tue Aug 20 11:44:49 CEST 2013
Ben Gamari wrote:
>> {-# LANGUAGE MultiParamTypeClasses #-}
>>
>> class Foo a b where
>>
>> bar :: a -> Int
>>
> The problem is in this declaration, which does not mention the type
> "b". This makes it impossible for the compiler to infer which instance
> to use when "bar" is used. This is what the compiler is trying to tell
> you when it says "The type variable `b1' is ambiguous".
Thanks, this works perfectly. Yet, to try to improve myself, I would like to
discuss a bit on the text of the two obtained errors in my example (correct
me if I am wrong below).
"""
test.hs:16:9:
No instance for (Foo Int b0) arising from a use of `bar'
"""
The second error is clear: indeed by calling `bar` on `4::Int`, we don't
indicate the type of b allowing to choose the right typeclass for the
implementation of the `bar` function. The fact there is only one typeclass
instance with Int as type for type variable `a` does not change anything:
Haskell does not look at the implemented instances. In other words,
”typeclasses are open”: more typeclasses with Int as first type variable
(and types different from `Int` for type variable `b`) may be added in the
future, and Haskell asks to specify which one is to use now, not in the
future. (Is this the right meaning for "typeclasses are open"?).
"""
test.hs:8:28:
Could not deduce (Foo a b1) arising from a use of `bar'
from the context (Foo a b)
bound by the class declaration for `Foo' at test.hs:(3,1)-(8,37)
The type variable `b1' is ambiguous
"""
Is this the same interpretation here? That is, even in the default
implementation of a typeclass function, Haskell does not suppose that the
instance of `bar` to use is the one of the considered instance?
Thanks a lot,
TP
More information about the Beginners
mailing list