[Haskell-cafe] confusion about 'instance'....

Jules Bean jules at jellybean.co.uk
Thu Jan 10 09:17:14 EST 2008


Nicholls, Mark wrote:
> Thanks for your response, I think you helped me on one of my previous
> abberations.
> 
> Hmmm....this all slightly does my head in....on one hand we have
> types....then type classes (which appear to be a relation defined on
> types)....then existential types...which now appear not to be treated
> quite in the same way as 'normal' types....and in this instance the
> syntax even seems to change....does 
> 
> "instance Num a => A a"

This means:

Given any type "a". Any type at all. Yes, ANY type "a", we accept that 
it might be an instance of A, and we add a "Num" context to the current 
inference.

So, supposing:  f :: (A a) => a -> b

and we're trying to type check:

f x

We first try to unify x's type with the type variable "a", which is 
easy. Then we impose the constraint "A a". At some later stage we will 
try to resolve this constraint. When we try to resolve it, we find that 
all types "a" are instances of A, but you have to add a Num constraint. 
So we add the Num constraint.

This behaviour is not what everyone wants, but it is a consequence of 
they type classes are specified.

GHC lets you turn off this behaviour somewhat with overlapping and 
undecidable instances but that's not really an ideal solution either.

The ideal solution to this precise case is probably just to make the Num 
class a superclass of A. That seems to do what you want.

Jules


More information about the Haskell-Cafe mailing list