[Haskell] type inference & instance extensions

Sittampalam, Ganesh ganesh.sittampalam at credit-suisse.com
Tue Jan 27 13:18:01 EST 2009

Corey O'Connor wrote:
> On Tue, Jan 27, 2009 at 4:51 AM,  <oleg at okmij.org> wrote:
>> Doug McIlroy wrote:
>>> A fragment of an attempt to make pairs serve as complex numbers,
>>> using ghc/hugs extensions: 
>>>         instance Num a => Num (a,a) where
>>>                 (x,y) * (u,v) = (x*u-y*v, x*v+y*u)
>> The recent versions of GHC have a nifty equality constraint, so the
>> code can be written simply
> I'm confused on why
> instance Num a => Num (a, a) where
> is not equivalent to
> instance (Num a, Num b, a ~ b) => Num (a, b) where
> I don't know the details of the type inference algorithm. What am I
> missing to understand why they are not the same? 

Type inference doesn't backtrack, and it starts by giving different
expressions different free type variables. So it doesn't initially
"know" that the two numeric literals in the tuple have the same type,
and so the instance ... => Num (a, a) doesn't apply - after all, there
might be some different instance where the two tuple elements are of
different types.

In contrast Num (a, b) will always apply, and only later do we discover
that we've forced a = b by selecting it. But that's fine as there's
no possibility of another Num instance for tuples (ignoring overlapping
instances for now).


Please access the attached hyperlink for an important electronic communications disclaimer: 


More information about the Haskell mailing list