为什么这些家庭实例声明会发生冲突?

时间:2013-07-11 12:44:01

标签: haskell type-families

我收到此代码的错误,我不明白冲突的位置。

{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances,
    UndecidableInstances #-}

import Codec.Gray (integralToGray, grayToIntegral)
import Data.List (foldl', unfoldr)
import Data.Word (Word8)
import Prelude hiding (read)

class Gene g where
  type Sequence g
  write :: Sequence g -> g -> Sequence g
  read :: Sequence g -> Maybe (g, Sequence g)

instance (Gene a, Sequence a ~ [k], Integral k, Gene k, Sequence k ~ [k]) => Gene [a] where
  type Sequence [a] = Sequence a -- LINE 15
  write xs gs = Nothing -- stub
  read xs = Nothing -- stub


class (Enum g, Bounded g) => Word8Enum g where
  writeEnum :: [Word8] -> g -> [Word8]
  writeEnum xs g = Nothing -- stub

  readEnum :: g -> [Word8] -> Maybe (g, [Word8])
  readEnum _ [] = Nothing
  readEnum model (x:xs) = Nothing -- stub

instance (Word8Enum g) => Gene g where
  type Sequence g = [Word8] -- LINE 29
  write = writeEnum
  read = readEnum undefined

当我将代码加载到GHC中时,出现以下错误:

λ> :l amy4
[1 of 1] Compiling Main             ( amy4.hs, interpreted )

amy4.hs:15:8:
    Conflicting family instance declarations:
      type Sequence [a] -- Defined at amy4.hs:15:8
      type Sequence g -- Defined at amy4.hs:29:8
Failed, modules loaded: none.

2 个答案:

答案 0 :(得分:6)

在诸如

之类的实例中
instance (Word8Enum g) => Gene g where
   ...

GHC在匹配实例时仅考虑实例箭头的右侧。即,不考虑约束。因此Gene g与任何其他实例重叠,特别是上面Gene [a]的实例。

在某些条件下允许重叠实例,但重叠的相关类型或类型系列不是(在某些限制情况下,它们将在即将发布的GHC版本中)。因此,您会收到两个Sequence声明的错误。

答案 1 :(得分:5)

有关在未来的GHC中允许重叠类型系列的信息,请参阅this ticket。 值得指出的是,使用closed type families,允许一些(大多数?全部?)重叠。例如,以下内容不能用作 open 类型系列:

type family NextListElt (xs :: [*]) (a :: *) :: *
type instance NextListElt (a ': b ': xs) a = b
type instance NextListElt (b ': c ': xs) a = NextListElt (c ': xs) a

但编译为封闭式家庭:

type family NextListElt (xs :: [*]) (a :: *) :: * where
  NextListElt (a ': b ': xs) a = b
  NextListElt (b ': c ': xs) a = NextListElt (c ': xs) a