Haskell: Can typeclasses define types (ala type traits)

haskell, typeclass

Solution

Take a look at type families.

{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}

class KeyTraits k where
    type KeyType k :: *
    key :: v -> KeyType k

data TableRow = TableRow { date :: Date, metaData :: String, value :: Int }

instance KeyTraits TableRow where
    type KeyType TableRow = Date
    key = date

data MyMap v = MyMap { getMap :: (KeyTraits v) => Map (KeyType v) v }

Problem

Is it possible to have a type be part of a typeclass? Something like: ``` class KeyTraits v where keyType :: * key :: v -> keyType data TableRow = { date :: Date, metaData :: String, value :: Int } instance KeyTraits TableRow where keyType = Date key = date ``` And can these "type-level" functions be used elsewhere? For example: ``` -- automatically deduce the type for the key, from the value type, using -- the typeclass data MyMap v = { getMap :: (KeyTraits v) => Map (keyType) v } ``` I may be doing something completely wrong, but I basically want the ability to define type relationships like the one above (e.g. Certain values already may have data that can be used as a Key). If that's not possible, or is difficult, could you suggest a better design that is more idiomatic? Thank you!

Original source