How to ignore data type parameters in class instances?

As a toy project, I would like to understand how to model math groups in Haskell in general.

To get us started, we start by observing that a, which will be defined Group, is simply a Monoidwith inversion.

class (Monoid m) => Group m where
    minvert :: m -> m

Then we first restrict ourselves to cyclic groups and begin by defining a cyclic group of order 12.

data Cyclic12 = Cyclic12 Int deriving (Show, Eq)

Finally, we instantiate both classes for Cyclic12.

instance Monoid Cyclic12 where
    mempty = Cyclic12 0
    mappend (Cyclic12 x) (Cyclic12 y) = Cyclic12 ((x + y) `mod` 12)

instance Group Cyclic12 where
    minvert (Cyclic12 x) = Cyclic12 ((0 - x) `mod` 12)

How can I separate the previous definition from a specific value of 12 to allow a more general definition of various cyclic groups?

Ideally, I would like to write type definitions

instance Monoid (Cyclic k) where
    mempty = Cyclic k 0
    mappend (Cyclic k x) (Cyclic k y) = Cyclic k ((x + y) `mod` k)

instance Group (Cyclic k) where
    minvert (Cyclic k x) = Cyclic k ((0 - x) `mod` k)

But with data definition, for example

data Cyclic = Cyclic Int Int deriving (Show, Eq)

, k " ". , , . .

+4
1

. - GHC.

{-# LANGUAGE DataKinds, KindSignatures, ScopedTypeVariables #-}

import GHC.TypeLits
import Data.Proxy (Proxy(..))

data Cyclic (n :: Nat) = Cyclic Integer deriving (Show, Eq)

:

instance KnownNat n => Monoid (Cyclic n) where
    mempty = Cyclic 0
    Cyclic x `mappend` Cyclic y = Cyclic $ (x + y) `mod` natVal (Proxy :: Proxy n)

instance KnownNat n => Group (Cyclic n) where
    minvert (Cyclic x) = Cyclic $ negate x `mod` natVal (Proxy :: Proxy n)

KnownNat , , n :: Nat , , natVal.

, GHCi:

ghci> :set -XDataKinds
ghci> type Z12 = Cyclic 12
ghci> mappend (Cyclic 8 :: Z12) (Cyclic 7 :: Z12)
Cyclic 3
ghci> minvert (Cyclic 4 :: Z12)
Cyclic 8

  • DataKinds n, . , (*). n Nat (n :: Nat).
  • KindSignatures n :: Nat, :: " " ( " " ), .
  • ScopedTypeVariables , n Proxy :: Proxy n , instance KnownNat m => Monoid (Cyclic n) where.
+8

Source: https://habr.com/ru/post/1678525/


All Articles