This problem actually emerged from attempt to implement few mathematical groups as types.
Cyclic groups have no problem (instance of Data.Group
defined elsewhere):
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))
But symmetric groups have some problem on defining some instances (implementation via factorial number system):
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
Error message from ghci (only briefly):
Overlapping instances for Enum (Symmetric (n - 1))
Overlapping instances for Bounded (Symmetric (n - 1))
So how can GHC know whether n-1
equals to 1 or not? I'd also like to know whether the solution can be written without FlexibleInstances
.