Search code examples
haskelltypestype-familiesderiving

Deriving `Eq` for a data type based on a type family in Haskell


I'm working with type-level programming in Haskell and have encountered an issue with deriving an Eq instance for a data type based on a type family.

Here's a simplified version of my code:

{-# LANGUAGE DataKinds, KindSignatures, TypeFamilies, DeriveGeneric #-}

data MyKind = Value1 | Value2
  deriving (Eq)

type family MyTypeFamily (k :: MyKind) :: * where
  MyTypeFamily 'Value1 = String
  MyTypeFamily 'Value2 = [Int]

data MyType (k :: MyKind) = MyType (MyTypeFamily k)
  deriving (Eq)

When attempting to compile this, I receive the following error:

• No instance for (Eq (MyTypeFamily k))
        arising from the first field of ‘MyType’ (type ‘MyTypeFamily k’)

My goal is to derive separate Eq and other instances for each value of MyKind, without manually writing them out. Since the options for MyKind are finite and all resolve to a type with Eq instance, this feels like it should be possible. I tried using quantified constraints, but received an error about an illegal type synonym family application.

Is there a way in Haskell to derive separate instances based on a type family without manually writing them out or specifying each kind value individually? If not is there a counterexample, why it can't be done?


Solution

  • Perhaps StandaloneDeriving will get you where you need to go (untested):

    deriving instance Eq (MyTypeFamily k) => Eq (MyType k)