File tree Expand file tree Collapse file tree 1 file changed +14
-0
lines changed Expand file tree Collapse file tree 1 file changed +14
-0
lines changed Original file line number Diff line number Diff line change 12
12
# # a denominator `den`, both of type int. The denominator can not be 0.
13
13
14
14
import math
15
+ import hashes
15
16
16
17
type Rational* [T] = object
17
18
# # a rational number, consisting of a numerator and denominator
@@ -205,6 +206,17 @@ proc abs*[T](x: Rational[T]): Rational[T] =
205
206
result .num = abs x.num
206
207
result .den = abs x.den
207
208
209
+ proc hash*[T](x: Rational[T]): THash =
210
+ ## Computes hash for rational `x`
211
+ # reduce first so that hash(x) == hash(y) for x == y
212
+ var copy = x
213
+ reduce(copy)
214
+
215
+ var h: THash = 0
216
+ h = h !& hash(copy.num)
217
+ h = h !& hash(copy.den)
218
+ result = !$h
219
+
208
220
when isMainModule :
209
221
var
210
222
z = Rational[int ](num: 0, den: 1)
@@ -242,11 +254,13 @@ when isMainModule:
242
254
assert( not(o > o) )
243
255
assert( cmp(o, o) == 0 )
244
256
assert( cmp(z, z) == 0 )
257
+ assert( hash(o) == hash(o) )
245
258
246
259
assert( a == b )
247
260
assert( a >= b )
248
261
assert( not(b > a) )
249
262
assert( cmp(a, b) == 0 )
263
+ assert( hash(a) == hash(b) )
250
264
251
265
var x = 1//3
252
266
You can’t perform that action at this time.
0 commit comments