[Haskell-cafe] duplicate instance declarations. Why?

Ryan Ingram ryani.spam at gmail.com
Fri Oct 24 05:40:22 EDT 2008

Instance instantiation is *not* search, and *not* similar to
subclassing in OO languages.

Both your instance declarations simply add constraints to functions that use it.

Here's a more concrete example:

class A a where
    doA :: a -> String
class R a where
    doR :: a -> String

instance R Int where doR = show
instance R a => A a where
    doA = doR

question x = doA x

The question is, what is the type of "question"?  Here are two valid
choices with this program:
question :: (A a) => a -> String
question :: (R a) => a -> String

The instance R a => A a says that every type "a" is an instance of
"A"; if an instance for A is needed, the compiler says "OK, I know how
to make one of those.  But I now add a new constraint, R a."

Adding another instance S a => A a makes the choice of what constraint
to add ambiguous.  In particular the following code does *not* work:

class S a where
    doS :: a -> String
instance S String where
    doS = id
instance S a => A a where
    doA = doS

question2 = question (2::Int)
question3 = question "3"

In my experience, if you are turning undecidable instances on and you
don't know exactly why it's safe to do so, there is probably a mistake
in your design.

   -- ryan

2008/10/24 Alberto G. Corona <agocorona at gmail.com>:
> with:
>>{-# OPTIONS -fglasgow-exts  -fallow-undecidable-instances  #-}
>>class A a
>>class R a
>>class S a
>>instance  R a => A a
>>instance S a => A a
> ----------
> GHC gives
> Duplicate instance declarations
>   instance  R a => A a
>   instance S a => A a
> Why?
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

More information about the Haskell-Cafe mailing list