Reputation: 23135
When I have code like the following:
class C where
type T t1 t2
...
instance C (X t) where
type T (X t) (t a b) = a
...
I get the error (with GHC head):
• Polymorphic type indexes of associated type ‘T’
(i.e. ones independent of the class type variables)
must be distinct type variables
Presumably this is because (t a b)
is not a simple variable like the error implies it should be.
But I can simply reorganise the code like the following:
type family T t1 t2
class C where
...
type instance T (X t) (t a b) = a
instance C (X t) where
....
And then everything seems to work fine now.
Because a slightly messier syntax, do I lose anything by taking type family definitions out of classes, or are in-class definitions just syntactic sugar so taking them out is a relatively cost free workaround?
Upvotes: 2
Views: 51
Reputation: 116139
This
type family T t1 t2
type instance T (X t) (t a b) = a
roughly works like this
class K t1 t1 where
type T t1 t2
instance K (X t) (t a b) where
type T (X t) (t a b) = a
Note how all the variables t1,t2
are parameters of class K
.
Indeed, this is required when variables occur more than once (i.e. non-linearly), as the posted error states:
• Polymorphic type indexes of associated type ‘T’
(i.e. ones independent of the class type variables)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
must be distinct type variables
So, either you add all these type variables to your class, or - to the same effect - you move the type family outside the class.
This compiles in GHC 8.0.
{-# LANGUAGE TypeFamilies, PolyKinds #-}
data X (t :: k) = X
class C t1 where
type T t1 t2
instance C (X (t :: * -> * -> *)) where
type T (X t) (t a b) = a
Upvotes: 4