summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorAndreas Rumpf <rumpf_a@web.de>2015-04-08 09:58:06 +0200
committerAndreas Rumpf <rumpf_a@web.de>2015-04-08 09:58:06 +0200
commitdfc3f9dcd77c7546d510dd168d79a917fce46994 (patch)
tree2fd6c084c7a5584f1a7043d5ba410b3fbc6d1e03 /lib
parenta4bbcf5ab0bef21bf0c2b6bb6bd5b57e3e2e1804 (diff)
parent46e6fd4fa99e17fb8e9e50a43d22e00b1a71cd99 (diff)
downloadNim-dfc3f9dcd77c7546d510dd168d79a917fce46994.tar.gz
Merge pull request #2486 from endragor/rational-hash
Add hash proc for Rational
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/rationals.nim14
1 files changed, 14 insertions, 0 deletions
diff --git a/lib/pure/rationals.nim b/lib/pure/rationals.nim
index 9682c0539..3b68a2381 100644
--- a/lib/pure/rationals.nim
+++ b/lib/pure/rationals.nim
@@ -12,6 +12,7 @@
 ## a denominator `den`, both of type int. The denominator can not be 0.
 
 import math
+import hashes
 
 type Rational*[T] = object
   ## a rational number, consisting of a numerator and denominator
@@ -205,6 +206,17 @@ proc abs*[T](x: Rational[T]): Rational[T] =
   result.num = abs x.num
   result.den = abs x.den
 
+proc hash*[T](x: Rational[T]): THash =
+  ## Computes hash for rational `x`
+  # reduce first so that hash(x) == hash(y) for x == y
+  var copy = x
+  reduce(copy)
+
+  var h: THash = 0
+  h = h !& hash(copy.num)
+  h = h !& hash(copy.den)
+  result = !$h
+  
 when isMainModule:
   var
     z = Rational[int](num: 0, den: 1)
@@ -242,11 +254,13 @@ when isMainModule:
   assert( not(o > o) )
   assert( cmp(o, o) == 0 )
   assert( cmp(z, z) == 0 )
+  assert( hash(o) == hash(o) )
 
   assert( a == b )
   assert( a >= b )
   assert( not(b > a) )
   assert( cmp(a, b) == 0 )
+  assert( hash(a) == hash(b) )
 
   var x = 1//3