diff options
author | Óscar Nájera <hi@oscarnajera.com> | 2021-04-05 18:53:15 +0200 |
---|---|---|
committer | Óscar Nájera <hi@oscarnajera.com> | 2021-04-05 18:53:15 +0200 |
commit | c9d3b981cd56d14450c2078980861153dd4920cc (patch) | |
tree | da735ff8d46b26fb2e270d1f093d209f8c96f1b0 | |
parent | c67c5d23114e079f9f5bd79f782b6c87dd73c640 (diff) | |
download | programmingbitcoin-c9d3b981cd56d14450c2078980861153dd4920cc.tar.gz programmingbitcoin-c9d3b981cd56d14450c2078980861153dd4920cc.tar.bz2 programmingbitcoin-c9d3b981cd56d14450c2078980861153dd4920cc.zip |
Instance FieldElement into Num typeclass
-rw-r--r-- | ecc.hs | 33 |
1 files changed, 15 insertions, 18 deletions
@@ -9,36 +9,33 @@ data FieldElement = instance Show FieldElement where show a = "FieldElement_" ++ show (prime a) ++ " " ++ show (number a) -add :: FieldElement -> FieldElement -> FieldElement -add (FieldElement a b) (FieldElement c d) - | b /= d = error "Distinct Fields" - | otherwise = FieldElement (mod (a + c) b) b - -sub :: FieldElement -> FieldElement -> FieldElement -sub (FieldElement a b) (FieldElement c d) - | b /= d = error "Distinct Fields" - | otherwise = FieldElement (mod (a - c) b) b - -mul :: FieldElement -> FieldElement -> FieldElement -mul (FieldElement a b) (FieldElement c d) - | b /= d = error "Distinct Fields" - | otherwise = FieldElement (mod (a * c) b) b - assert :: Bool -> Bool assert False = error "WRONG" assert x = x +instance Num FieldElement where + (FieldElement a b) + (FieldElement c d) + | b /= d = error "Distinct Fields" + | otherwise = FieldElement (mod (a + c) b) b + (FieldElement a b) * (FieldElement c d) + | b /= d = error "Distinct Fields" + | otherwise = FieldElement (mod (a * c) b) b + abs a = a + signum _ = 1 + negate (FieldElement a b) = FieldElement (mod (b - a) b) b + fromInteger _ = error "can't transform" + aa = let a = FieldElement 2 31 b = FieldElement 15 31 in assert (and - [ add a b == FieldElement 17 31 + [ a + b == FieldElement 17 31 , a /= b - , sub a b == FieldElement 18 31 + , a - b == FieldElement 18 31 ]) bb = let a = FieldElement 19 31 b = FieldElement 24 31 - in mul a b + in a * b |