summary refs log tree commit diff stats
path: root/lib/pure/rationals.nim
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/pure/rationals.nim
parentd170a51f544536522625bf9ca2b6e0a7f80427f7 (diff)
downloadNim-46e6fd4fa99e17fb8e9e50a43d22e00b1a71cd99.tar.gz
Added hash proc for Rational
Diffstat (limited to 'lib/pure/rationals.nim')
-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
 
96' href='#n196'>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