haskelltype-families

Instance of class with Data family yielding error "Couldn't match expected type"


I'm loading a file containing this code into GHCi version 9.2.8:

{-# LANGUAGE TypeFamilies #-}

import Data.Kind ( Type )

class Record rec where
  data Ident rec :: Type
  create :: rec -> Ident rec

newtype Person = Person { name :: String } deriving Show

instance Record Person where
  data Ident Person = String
  create p = ""

and I get the following error:

Record.hs:13:14: error:
    • Couldn't match type: [Char]
                     with: Ident Person
      Expected: Ident Person
        Actual: String
    • In the expression: ""
      In an equation for ‘create’: create p = ""
      In the instance declaration for ‘Record Person’

If I replace "" with undefined, I can load the file and run :info Person, which gives me, among other lines, this:

data instance Ident Person = String 

That seems to me like it ought to match.

What am I doing wrong here? Thank you!


Solution

  • data Ident Person = String defines a new data type with only a single value, named String. Here String is a constructor name, and has nothing to do with the String type.

    By contrast, data Ident Person = K String defines a data type with constructor K :: String -> Ident Person. If you use that, you will need to explicitly apply/remove K to transform String into Ident Person and vice versa.

    If instead you intend Ident Person to be exactly the same type as String, then use type families, e.g. type Ident a :: Type and type Ident Person = String.