fork download
  1.  
  2. {-# LANGUAGE FlexibleInstances #-}
  3.  
  4. {-# LANGUAGE GeneralizedNewtypeDeriving #-}
  5.  
  6. -- {-# LANGUAGE DerivingVia #-}
  7.  
  8.  
  9. -- Finite Field 6
  10.  
  11. newtype ToFF a = ToFF a deriving ( Eq, Integral, Real , Enum ,Ord )
  12.  
  13. newtype ToWM a = ToWM a deriving ( Eq, Enum, Real, Ord, Integral, Num ) -- ( Eq, Integral, Real , Enum ,Ord )
  14.  
  15. instance ( Show a ) => Show ( ToWM a ) where
  16. show ( ToWM x ) = dropWhile ( == ' ' ) $ dropWhile (/=' ' ) $ show x
  17. --show ( ToWM x ) = show x
  18.  
  19. class WithModulus a where
  20. modulus :: a -> Integer
  21.  
  22. instance ( WithModulus a, Num a, Integral a ) => Num ( ToFF a ) where
  23. ( ToFF x ) + ( ToFF y ) = ToFF $ mod ( x + y ) ( fromInteger $ modulus x )
  24. ( ToFF x ) - ( ToFF y ) = ToFF $ mod ( x - y ) ( fromInteger $ modulus x )
  25. ( ToFF x ) * ( ToFF y ) = ToFF $ mod ( x * y ) ( fromInteger $ modulus x )
  26. signum ( ToFF x ) = ToFF $ signum x
  27. abs ( ToFF x ) = ToFF $ abs x
  28.  
  29. instance ( WithModulus a, Show a ) => Show ( ToFF a ) where
  30. --show ( ToFF x ) = dropWhile ( == ' ' ) $ dropWhile (/=' ' ) $ show x
  31. show ( ToFF x ) = show x
  32.  
  33.  
  34.  
  35. {-
  36. ひとつの標数につ1個の整数型の型を用意する
  37. 用意する型は
  38. ( Eq, Num, Integral, Real, Ord, Enum ,Show )
  39. のインスタンスであるとする
  40. 以下それをBTP型とする
  41. ToWM BTP型にWithModulusクラスを継承する
  42. その際メンバ関数modurusは引数によらす標数を返す関数として定義しておく
  43. ToFF ( ToWM BTP )型が有限素体の計算を行う型として使える
  44. これには( Eq, Num, Integral, Real, Ord, Enum ,Show )のインスタンスが自動的に付与される
  45. -}
  46. ------ 𝔽₅------
  47. newtype BT65537 = BT65537 Integer deriving ( Eq, Num, Integral, Real, Ord, Enum ,Show )
  48.  
  49. instance WithModulus ( ToWM BT65537 ) where
  50. modulus _ = 65537
  51.  
  52. newtype F65537 = F65537 ( ToFF ( ToWM BT65537 ) ) deriving ( Eq, Num, Integral, Real, Ord, Enum ,Show )
  53.  
  54. ------ 𝔽₂₅₇------
  55. newtype BT257= BT257 Int deriving ( Eq, Num, Integral, Real, Ord, Enum ,Show )
  56.  
  57. instance WithModulus ( ToWM BT257 ) where
  58. modulus _ = 257
  59.  
  60. newtype F257 = F257 ( ToFF ( ToWM BT257) ) deriving ( Eq, Num, Integral, Real, Ord, Enum ,Show )
  61.  
  62. ------ 𝔽₆₅₅₃₇------
  63. newtype BT5= BT5 Integer deriving ( Eq, Num, Integral, Real, Ord, Enum ,Show )
  64.  
  65. instance WithModulus ( ToWM BT5 ) where
  66. modulus _ = 5
  67.  
  68. newtype F5 = F5( ToFF ( ToWM BT5) ) deriving ( Eq, Num, Integral, Real, Ord, Enum ,Show )
  69.  
  70. main = do
  71. print $ ( F5 3 )^4
  72. print $ ( F257 3 )^256
  73. print $ product [ F257 1..F257 256 ]
  74. print $ product [ F65537 1..F65537 65536 ]
  75.  
Success #stdin #stdout 0.01s 5544KB
stdin
Standard input is empty
stdout
F5 1
F257 1
F257 256
F65537 65536