summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorRuslan Mustakov <endragorr@gmail.com>2015-04-08 00:52:20 +0600
committerRuslan Mustakov <endragorr@gmail.com>2015-04-08 00:52:20 +0600
commit46e6fd4fa99e17fb8e9e50a43d22e00b1a71cd99 (patch)
treedcb164c82a900dd50e0113e707affebeefa1f436 /lib
parentd170a51f544536522625bf9ca2b6e0a7f80427f7 (diff)
downloadNim-46e6fd4fa99e17fb8e9e50a43d22e00b1a71cd99.tar.gz
Added 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 4f30ab24f..4e28e931a 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