Skip to content

Commit dfc3f9d

Browse files
committed
Merge pull request #2486 from endragor/rational-hash
Add hash proc for Rational
2 parents a4bbcf5 + 46e6fd4 commit dfc3f9d

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

lib/pure/rationals.nim

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
## a denominator `den`, both of type int. The denominator can not be 0.
1313

1414
import math
15+
import hashes
1516

1617
type Rational*[T] = object
1718
## a rational number, consisting of a numerator and denominator
@@ -205,6 +206,17 @@ proc abs*[T](x: Rational[T]): Rational[T] =
205206
result.num = abs x.num
206207
result.den = abs x.den
207208
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+
208220
when isMainModule:
209221
var
210222
z = Rational[int](num: 0, den: 1)
@@ -242,11 +254,13 @@ when isMainModule:
242254
assert( not(o > o) )
243255
assert( cmp(o, o) == 0 )
244256
assert( cmp(z, z) == 0 )
257+
assert( hash(o) == hash(o) )
245258
246259
assert( a == b )
247260
assert( a >= b )
248261
assert( not(b > a) )
249262
assert( cmp(a, b) == 0 )
263+
assert( hash(a) == hash(b) )
250264
251265
var x = 1//3
252266

0 commit comments

Comments
 (0)