这个问题实际上是由于尝试将少数数学群实现为类型而出现的。
循环群没有问题(实例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还是不等于1?我还想知道是否可以在不使用的情况下编写解决方案FlexibleInstances
.
Add Bounded (Symmetric (n-1))
and 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
(在我看来,这不值得,FlexibleInstances
是良性扩展),使用皮亚诺数data Nat = Z | S Nat
而不是 GHC 的原始表示。首先更换实例头Bounded (Symmetric n)
with 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 ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)