-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ring.hs
306 lines (270 loc) · 11.1 KB
/
Ring.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
-- | Dieses Modul stellt die zentrale Typklasse 'Ring' für kommutative Ringe
-- mit Eins und einige spezialisierte Klassen zur Verfügung.
{-# LANGUAGE FlexibleInstances, TypeFamilies, FlexibleContexts #-}
module Ring
( -- * Typklassen für Ringe und Ringe mit bestimmten Eigenschaften
Ring(..), (-), IntegralDomain, OrderedRing
, HasTestableAssociatedness(..), HasRationalEmbedding(..)
-- * Ringe mit einer "komplexen Konjugation"
, HasConjugation(..), absSq
-- * Näherungen für Debugging-Zwecke
, HasFloatingApprox(..)
-- * Allgemeine Funktionen für Ringe
, sum, product, (^)
-- * QuickCheck-Eigenschaften
, props_ringAxioms, props_areAssociated
, check_Ring
) where
import Prelude hiding ((+), (-), (*), (/), (^), negate, recip, fromRational, quotRem, fromInteger, sum, product)
import qualified Prelude as P
import qualified Data.Complex as C
import Data.Ratio
import Nat
import Proxy
import Testing
-- | Klasse für Typen, die Ringe repräsentieren.
-- Dabei meinen wir stets kommutative Ringe mit Eins.
class Ring a where
-- | Addition.
(+) :: a -> a -> a
-- | Negation.
negate :: a -> a
-- | Multiplikation.
(*) :: a -> a -> a
-- | Null.
zero :: a
-- | Eins.
unit :: a
-- | /fromInteger z/ soll das Bild von /z/ unter dem eindeutigen
-- Ringhomomorphismus vom Ring der ganzen Zahlen in /a/, also
-- /z 1/, sein.
fromInteger :: Integer -> a
infixl 6 +
infixl 7 *
-- | Bei der Rechnung mit Polynomen sammeln sich manchmal abschließende
-- Null-Koeffizienten an, die weggelassen werden könnten. Da wir nicht
-- fordern wollen, dass jeder Ring diskret ist (etwa weil das nicht stimmt
-- oder der Test auf Gleichheit teuer ist), gehen wir hier einen
-- Kompromiss:
--
-- Ein Ring kann die Methode 'couldBeNonZero' implementieren.
-- Diese soll nur dann 'False' zurückliefern, wenn das übergebene
-- Ringelement null ist. Sie ist aber nicht gezwungen, in diesem
-- wirklich 'False' zurückzugeben -- in der Tat ist die
-- Standardimplementierung einfach
--
-- > couldBeNonZero = const True.
--
-- Die zu erfüllende Spezifikation ist also:
--
-- > couldBeNonZero x == False ==> x == zero.
--
-- Ringe, für die es einen effizienten Gleichheitstest mit Null gibt,
-- können 'couldBeNonZero' entsprechend besser definieren.
couldBeNonZero :: a -> Bool
couldBeNonZero = const True
-- | Subtraktion, erfüllt folgende Spezifikation:
--
-- > x - y = x + negate y.
(-) :: (Ring a) => a -> a -> a
x - y = x + negate y
infixl 6 -
newtype RejectZero a = MkRejectZero a
deriving (Show,Eq)
instance (Ring a, Eq a, Arbitrary a) => Arbitrary (RejectZero a) where
arbitrary = do
x <- arbitrary
return $ if x == zero
then MkRejectZero unit
else MkRejectZero x
shrink (MkRejectZero x) = map MkRejectZero . shrink $ x
props_ringAxioms :: (Ring a, Eq a, Arbitrary a, Show a) => Proxy a -> [Property]
props_ringAxioms a = concat
[ props_commutativeGroup (+) (zero `asTypeOfProxy` a) negate
, [ property $ \x y z -> typ x && x * (y * z) == (x * y) * z ]
, [ property $ \x -> typ x && x * unit == x ]
, [ property $ \x y -> typ x && x * y == y * x ]
, [ property $ \x y z -> typ x && x * (y + z) == x * y + x * (z `asTypeOfProxy` a) ]
]
where typ x = let _ = x `asTypeOfProxy` a in True
props_commutativeMonoid :: (Eq a, Show a, Arbitrary a) => (a -> a -> a) -> a -> [Property]
props_commutativeMonoid (#) nul =
[ property $ \x y z -> x # (y # z) == (x # y) # z
, property $ \x -> x # nul == x
, property $ \x y -> x # y == y # x
]
props_commutativeGroup :: (Eq a, Show a, Arbitrary a) => (a -> a -> a) -> a -> (a -> a) -> [Property]
props_commutativeGroup (#) nul neg =
props_commutativeMonoid (#) nul ++ [ property $ \x -> x # neg x == nul ]
-- | Klasse für Typen, die Integritätsbereiche repräsentieren, also
-- für alle /x/ folgende Bedingung erfüllen: /Entweder/ ist /x/ null,
-- /oder/ /x/ ist regulär (d.h. die Multiplikationsabbildung mit /x/ ist
-- injektiv).
--
-- Aus dieser Definition folgt sofort, dass Gleichheit im Ring entscheidbar
-- (für gegebene Ringelemente /x/, /y/ muss nur die Frage stellen, ob /x-y/
-- null oder regulär ist), daher fordern wir die Zugehörigkeit zur
-- /Eq/-Typklasse.
--
-- Bestimmte Methoden muss ein Typ, der zur 'IntegralDomain'-Klasse gehören
-- möchte, nicht haben: Denn da in einem Integritätsbereich ein Element genau dann
-- regulär ist, wenn es nicht null ist, wird die geforderte Entscheidungsfähigkeit
-- schon durch '(==)' von 'Eq' geliefert.
class (Ring a, Eq a) => IntegralDomain a
-- | Klasse für geordnete Ringe, also Ringe mit einer totalen Relation
-- /(<=)/ (reflexiv, transitiv, antisymmetrisch, je zwei Elemente
-- vergleichbar), die folgende zwei Kompatibilitätsaxiome erfüllt:
--
-- > a <= b ==> a + c <= b + c
-- > 0 <= a, 0 <= b ==> 0 <= ab.
class (Ring a, Ord a) => OrderedRing a
-- | Klasse für Ringe, in denen entscheidbar ist, ob zwei gegebene Elemente
-- /x/ und /y/ zueinander assoziiert sind, ob es also ein invertierbares
-- Element /u/ mit /y = ux/ gibt.
class (Ring a) => HasTestableAssociatedness a where
-- | /areAssociated x y/ soll genau dann /False/ sein, wenn 'x'
-- und 'y' nicht zueinander assoziiert sind, und andernfalls
-- /Just u/ zurückgeben, wobei /u/ ein invertierbares Element
-- mit /y = ux/ (in dieser Reihenfolge) ist.
--
-- Richtiger wäre es, den Rückgabetyp auf eine monadischen Typ
-- abzuschwächen; in den in diesem Projekt betrachteten Fällen können wir
-- aber in der Tat sogar den von diesem Typ geforderten funktionalen
-- Zusammenhang bieten.
areAssociated :: a -> a -> Maybe a
props_areAssociated :: (HasTestableAssociatedness a, Eq a, Show a, Arbitrary a) => Proxy a -> [Property]
props_areAssociated a =
[ property $ \x y ->
case areAssociated x y of
Nothing -> True -- ungenau!
Just u -> y == u * x
where _ = x `asTypeOfProxy` a
]
-- | Klasse für Ringe, die eine (dann eindeutige) Einbettung der rationalen
-- Zahlen zulassen.
class (Ring a) => HasRationalEmbedding a where
-- | /fromRational q/ soll das Bild von /q/ unter der Einbettung der
-- rationalen Zahlen in den Ring /a/ sein.
fromRational :: Rational -> a
-- | Klasse für Ringe, in denen der Begriff der komplexen Konjugation definiert
-- ist.
class (Ring a, Ring (RealSubring a)) => HasConjugation a where
-- | Zugehöriger Unterring der reellen Elemente, also solcher, die von
-- der komplexen Konjugation invariant gelassen werden.
type RealSubring a :: *
-- | Konjugiert ein Ringelement.
conjugate :: a -> a
-- | Liefert die imaginäre Einheit.
imagUnit :: a
-- | Liefert den Realteil.
--
-- Daraus wird dann auch 'absSq' und 'imagPart' definiert.
realPart :: a -> RealSubring a
-- | Bestimmt den Imaginärteil einer Zahl.
--
-- Ist vordefiniert über 'realPart'; wenn das zu einer
-- nicht-terminierenden Rekursion führt, muss die Instanz eine geeignete
-- andere Definition gebeen.
imagPart :: a -> RealSubring a
imagPart = negate . realPart . (imagUnit *)
-- | Berechnet das Betragsquadrat einer Zahl /z/, also
-- das Produkt von /z/ mit seinem komplex Konjugierten.
absSq :: (HasConjugation a) => a -> RealSubring a
absSq z = realPart $ z * conjugate z
-- | Klasse für Ringe, die für Debuggingzwecke eine Approximation durch
-- komplexe Fließkommazahlen zulassen.
class HasFloatingApprox a where
-- | Liefert eine Approximation durch eine komplexe Fließkommazahl.
-- Diese Methode ist nur für Debuggingzwecke gedacht; die Wahl der
-- Genauigkeit bleibt den Instanzen überlassen. Auch muss 'unsafeApprox'
-- nicht referentiell-transparent sein.
unsafeApprox :: a -> C.Complex Double
-- | Summiert eine endliche Liste von Ringelementen, mit der Konvention
-- /sum [] = zero/.
sum :: (Ring a) => [a] -> a
sum = sum' zero
where
sum' acc [] = acc
sum' acc (x:xs) = let y = acc + x in seq y $ sum' y xs
-- | Multipliziert eine endliche Liste von Ringelementen, mit der Konvention
-- /product [] = unit/.
product :: (Ring a) => [a] -> a
product = product' unit
where
product' acc [] = acc
product' acc (x:xs) = let y = acc * x in seq y $ product' y xs
-- | Potenziert ein gegebenes Ringelement mittels binärer Exponentiation
-- (square and multiply).
--
-- Quelle: Das Haskell-Prelude.
(^) :: (Ring a) => a -> Nat -> a
_ ^ 0 = unit
z ^ m | m > 0 = f z (m-1) z
where f _ 0 y = y
f x n y = g x n where
g u k | even k = g (u*u) (k `quot` 2)
| otherwise = f u (k-1) (u*y)
_ ^ _ = error "Ring.^: Negativer Exponent"
infixr 8 ^
-- Die größenbeschränkten Ganzzahlen bilden einen bestimmten Faktorring
-- des echten Rings der ganzen Zahlen.
instance Ring Int where
(+) = (P.+)
(*) = (P.*)
zero = 0
unit = 1
negate = P.negate
fromInteger = P.fromInteger
couldBeNonZero = (/= 0)
instance HasFloatingApprox Int where
unsafeApprox = fromIntegral
-- Der richtige Ring aller ganzen Zahlen, ohne Größenbeschränkung.
instance Ring Integer where
(+) = (P.+)
(*) = (P.*)
zero = 0
unit = 1
negate = P.negate
fromInteger = P.fromInteger
couldBeNonZero = (/= 0)
instance IntegralDomain Integer
instance HasTestableAssociatedness Integer where
areAssociated x y
| abs x == abs y = Just (signum x * signum y)
| otherwise = Nothing
instance HasFloatingApprox Integer where
unsafeApprox = fromIntegral
-- Quotientenkörper.
-- Die Integral-Beschränkung stammt von
instance (IntegralDomain a, Integral a) => Ring (Ratio a) where
(+) = (P.+)
(*) = (P.*)
zero = 0
unit = 1
negate = P.negate
fromInteger = P.fromInteger
couldBeNonZero = (/= 0)
instance (IntegralDomain a, Integral a) => IntegralDomain (Ratio a)
instance (IntegralDomain a, Integral a) => HasTestableAssociatedness (Ratio a) where
areAssociated x y
| x == zero && y == zero = Just 1
| x /= zero && y /= zero = Just (y * P.recip x)
| otherwise = Nothing
instance (IntegralDomain a, Integral a) => HasRationalEmbedding (Ratio a) where
fromRational z =
let (p,q) = (numerator z, denominator z)
in fromInteger p * P.recip (fromInteger q)
instance (IntegralDomain a, Integral a, HasFloatingApprox a) => HasFloatingApprox (Ratio a) where
unsafeApprox x =
let (p,q) = (numerator x, denominator x)
in unsafeApprox p P./ unsafeApprox q
instance OrderedRing (Ratio Integer)
check_Ring :: IO ()
check_Ring = mapM_ quickCheck $ concat
[ props_ringAxioms (undefined :: Proxy Integer)
, props_ringAxioms (undefined :: Proxy Int)
, props_ringAxioms (undefined :: Proxy Rational)
, props_areAssociated (undefined :: Proxy Integer)
, props_areAssociated (undefined :: Proxy Rational)
, [ property $ \x n -> n >= 1 ==> x^n == x^(n-1) * (x :: Rational) ]
]