我現在有一些代碼創建了n階的素數域,並具有計算加法,乘法和它們逆的所有必要函數。它工作正常,但我真的希望能夠重載+, - ,*,/和Integral和Num中綴函數,但我不知道如何執行此操作。以下是我當前的代碼:Haskell中的Prime有限域(Z/pZ),帶有運算符重載
import Data.Maybe
data FiniteField = FiniteField {add::(FieldElement -> FieldElement -> FieldElement),
addinv::(FieldElement -> FieldElement),
mul::(FieldElement -> FieldElement -> FieldElement),
mulinv::(FieldElement -> FieldElement),
new::(Integer -> FieldElement)
}
newtype FieldElement = FieldElement Integer deriving (Eq, Show, Read)
toInt :: FieldElement -> Integer
toInt (FieldElement x) = x
gcdExt :: Integer -> Integer -> (Integer, Integer, Integer)
gcdExt a 0 = (1, 0, a)
gcdExt a b = (t, s - q * t, g)
where (q, r) = quotRem a b
(s, t, g) = gcdExt b r
modMulInv :: Integer -> Integer -> Integer
modMulInv a n = i
where (i, _, _) = gcdExt a n
isPrimeLoop :: Integer -> Integer -> Bool
isPrimeLoop n i
| i == n = True
| i == 2 = (mod n i /= 0) && isPrimeLoop n (i+1)
| otherwise = (mod n i /= 0) && isPrimeLoop n (i+2)
isPrime :: Integer -> Bool
isPrime n = isPrimeLoop n 2
newFiniteField :: Integer -> Maybe FiniteField
newFiniteField n
| not (isPrime n) = Nothing
| otherwise = Just (FiniteField add addinv mul mulinv new)
where
add = (\x y -> FieldElement (mod (toInt x + toInt y) n))
addinv = (\x -> FieldElement (mod (n - toInt x) n))
mul = (\x y -> FieldElement (mod (toInt x * toInt y) n))
mulinv = (\x -> FieldElement (mod (modMulInv (toInt x) n) n))
new = (\x -> FieldElement x)
有什麼辦法改變設計,允許我使用'民'? –
@IzaakWeiss有很多選項 - 我在最後12分鐘左右的編輯中涵蓋了其中的一些選項。 – Carl