关联类型系列失败,独立时工作

时间:2016-07-21 13:14:59

标签: haskell type-families associated-types

当我有以下代码时:

class C where
  type T t1 t2
  ...

instance C (X t) where
  type T (X t) (t a b) = a
  ...

我收到错误(GHC负责人):

• Polymorphic type indexes of associated type ‘T’
    (i.e. ones independent of the class type variables)
    must be distinct type variables

大概这是因为(t a b)不是一个简单的变量,就像错误所暗示的那样。

但我可以简单地重新组织代码,如下所示:

type family T t1 t2

class C where
  ...

type instance T (X t) (t a b) = a

instance C (X t) where
  ....

然后现在一切似乎都很好。

因为语法略显混乱,我是否会通过从类中取出类型族定义而丢失任何内容,或者是类内定义只是语法糖,因此将它们取出是一种相对无成本的解决方法?

1 个答案:

答案 0 :(得分:4)

type family T t1 t2
type instance T (X t) (t a b) = a

大致像这样工作

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

请注意所有变量t1,t2如何是类K的参数。 实际上,当变量出现不止一次(即非线性)时,这是必需的,因为发布的错误表明:

• Polymorphic type indexes of associated type ‘T’
    (i.e. ones independent of the class type variables)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    must be distinct type variables

因此,要么将所有这些类型变量添加到类中,要么 - 为了同样的效果 - 将类型族移到类外。

这在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