Haskell: instance definitions for type families

Let's say we have the following code:

class C t where
  g :: t

instance C Int where
  g = 42

Simple We can also define functions on Int like this:

f1 :: Int -> Int
f1 x = x * x

I work with type families, in particular, because I Data.Hasuse them, and I want to insert them into IxSet.

But here I will give a simplified example. Suppose we want to define a new type Xthat is similar to Int. We could do this:

type family X
type instance X = Int

Then we can define functions on Xas follows:

f2 :: X -> X
f2 x = x * x + 1

There are no problems so far. Now try to determine the instance C Xas it was done for C Int:

instance C X where
  g = 43

Uh oh, now we have the following error:

Invalid family synonym type application: X
In instance declaration for'C X'

Now try something else:

newtype NewX = NewX X

instance C NewX where
  g = 43

, :

(Num NewX)
   '43'

, newtype , . , newtype, .

, , ?


:

, , :

import Data.Has
import Data.IxSet

data Col1 = Col1; type instance TypeOf Col1 = Text
data Col2 = Col2; type instance TypeOf Col2 = Text

type Row = FieldOf Col1 :&: FieldOf Col2;

instance Indexable Row where
  empty = ixSet [ixFun $ (\x -> [ Col1 ^. x ]) ] -- Maybe add some more indexes later

:

: Row
'Indexable Row'

Row a newtype :

( ( Col1))    `^. ' :      ( Col1)

, , - :

newtype Row = Row (FieldOf Col1 :&: FieldOf Col2)
  deriving 
  (
    Contains (Labelled Col1 Text), -- Add this for every column
    Contains (Labelled Col2 Text)  -- ...
  )

, "typedef" Contains (Labelled x (TypeOf x)) HasCol x, .

+2
2

A newtype : , type . ,

instance C NewX where
   g = NewX  43

Instance, , ( ) . , newtype . ,

newtype Row = Row {runRow :: FieldOf Col1 :&: FieldOf Col2}

instance Indexable Row where
  empty = ixSet [ixFun $ (\x -> [ Col1 ^. (runRow x) ]) ]

, GeneralizedNewtypeDeriving . , , , , , .


(Question asker):

, Row

newtype Row = Row ( FieldOf Col1 :&: FieldOf Col2 )

instance Indexable Row where
  empty = ixSet [ixFun $ (\(Row x) -> [ Col1 ^. x ]) ]
+3

:

{-# LANGUAGE GeneralizedNewtypeDeriving, TypeFamilies #-}

class C a where g :: a
type family X
type instance X = Int
newtype NewX = NewX X deriving Num
instance C NewX where g = 43
+5

All Articles