Duplicate Instances [GHC-59692]
You can only define a single instance for every type, because it must be possible to automatically resolve class constraints without any ambiguity.
If the instances are identical, you should simply remove one.
If you want multiple instances for the same type, you can circumvent this restriction by introducing a newtype
wrapper. An example of this is shown in the solution for the “Multiple Instances for Semigroup Int” example.
Note that instances are considered the same even if they have different constraints. Only the arguments of the class are considered when matching instances. This issue is shown in the “Identical Instance Heads” example.
See the GHC User Guide for more information on instance declarations and resolution.
Examples
Identical Instance Heads
Even though the instances have different constraints, they are still considered the same.
Error message
messages/GHC-59692/example1/before/Example1.hs:3:10: error: [GHC-59692]
Duplicate instance declarations:
instance Eq a => Eq (T a)
-- Defined at messages/GHC-59692/example1/before/Example1.hs:3:10
instance Show a => Eq (T a)
-- Defined at messages/GHC-59692/example1/before/Example1.hs:6:10
|
3 | instance Eq a => Eq (T a) where
| ^^^^^^^^^^^^^^^^
Example1.hs
module Example1 where
data T a
instance Eq a => Eq (T a) where
(==) = (==)
instance Show a => Eq (T a) where
(==) = (==)
module Example1 where
data T a
instance Eq a => Eq (T a) where
(==) = (==)
Multiple Instances for Semigroup Int
Haskell does not allow to give more than one definition of Semigroup Int
, even though we might want to provide both an instance for the semigroup given by multiplication and the semigroup given by addition.
If we require both instances, then we should define two newtype
wrappers for Int
.
MultipleInstances.hs
module MultipleInstances where
instance Semigroup Int where
(<>) = (+)
instance Semigroup Int where
(<>) = (*)
module MultipleInstances where
newtype Sum = Sum { getSum :: Int }
instance Semigroup Sum where
(<>) x y = Sum (getSum x + getSum y)
newtype Product = Product { getProduct :: Int }
instance Semigroup Product where
(<>) x y = Product (getProduct x * getProduct y)