Duplicate Instances [GHC-59692]

For type class coherence, at most one instance may be defined for each type for the same type class.

Identical instances should simply be removed. If multiple instances for the same type are required, circumventing this restriction is possible by introducing a newtype wrapper.

Examples

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
Before
module MultipleInstances where

instance Semigroup Int where
    (<>) = (+)

instance Semigroup Int where
    (<>) = (*)
After
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)