通过Nat-kind重叠实例

时间:2019-01-02 02:42:03

标签: haskell math gadt data-kinds overlapping-instances

这个问题实际上是由于尝试将几个数学组实现为类型而引起的。

循环组没有问题(Data.Group的实例在其他地方定义)

newtype Cyclic (n :: Nat) = Cyclic {cIndex :: Integer} deriving (Eq, Ord)

cyclic :: forall n. KnownNat n => Integer -> Cyclic n
cyclic x = Cyclic $ x `mod` toInteger (natVal (Proxy :: Proxy n))

但是对称组在定义某些实例时存在一些问题(通过阶乘数系统实现):

infixr 6 :.

data Symmetric (n :: Nat) where
    S1 :: Symmetric 1
    (:.) :: (KnownNat n, 2 <= n) => Cyclic n -> Symmetric (n-1) -> Symmetric n

instance {-# OVERLAPPING #-} Enum (Symmetric 1) where
    toEnum _ = S1
    fromEnum S1 = 0

instance (KnownNat n, 2 <= n) => Enum (Symmetric n) where
    toEnum n = let
        (q,r) = divMod n (1 + fromEnum (maxBound :: Symmetric (n-1)))
        in toEnum q :. toEnum r
    fromEnum (x :. y) = fromInteger (cIndex x) * (1 + fromEnum (maxBound `asTypeOf` y)) + fromEnum y

instance {-# OVERLAPPING #-} Bounded (Symmetric 1) where
    minBound = S1
    maxBound = S1

instance (KnownNat n, 2 <= n) => Bounded (Symmetric n) where
    minBound = minBound :. minBound
    maxBound = maxBound :. maxBound

ghci的错误消息(仅简短地):

Overlapping instances for Enum (Symmetric (n - 1))
Overlapping instances for Bounded (Symmetric (n - 1))

那么,GHC如何知道n-1是否等于1?我也想知道是否可以不用FlexibleInstances来编写解决方案。

1 个答案:

答案 0 :(得分:3)

添加Bounded (Symmetric (n-1))Enum (Symmetric (n-1))作为约束,因为要完全解决这些约束将需要知道n的确切值。

instance (KnownNat n, 2 <= n, Bounded (Symmetric (n-1)), Enum (Symmetric (n-1))) =>
  Enum (Symmetric n) where
  ...

instance (KnownNat n, 2 <= n, Bounded (Symmetric (n-1))) =>
  Bounded (Symmetric n) where
  ...

为避免使用FlexibleInstances(这不值得IMO使用,FlexibleInstances是良性扩展),请使用Peano数字data Nat = Z | S Nat代替GHC的原始表示形式。首先用Bounded (Symmetric n)替换实例头Bounded (Symmetric (S (S n')))(这起约束2 <= n的作用),然后用辅助类(可能更多)分解实例以满足标准要求在实例头上。可能看起来像这样:

instance Bounded_Symmetric n => Bounded (Symmetric n) where ...
instance Bounded_Symmetric O where ...
instance Bounded_Symmetric n => Bounded_Symmetric (S n) where ...