diff options
-rw-r--r-- | lib/pure/rationals.nim | 7 | ||||
-rw-r--r-- | tests/rational/trat_float.nim | 9 | ||||
-rw-r--r-- | tests/rational/trat_init.nim | 10 |
3 files changed, 23 insertions, 3 deletions
diff --git a/lib/pure/rationals.nim b/lib/pure/rationals.nim index 60d09c71a..7d9241412 100644 --- a/lib/pure/rationals.nim +++ b/lib/pure/rationals.nim @@ -18,8 +18,9 @@ type Rational*[T] = object ## a rational number, consisting of a numerator and denominator num*, den*: T -proc initRational*[T](num, den: T): Rational[T] = +proc initRational*[T:SomeInteger](num, den: T): Rational[T] = ## Create a new rational number. + assert(den != 0, "a denominator of zero value is invalid") result.num = num result.den = den @@ -33,7 +34,7 @@ proc `$`*[T](x: Rational[T]): string = ## Turn a rational number into a string. result = $x.num & "/" & $x.den -proc toRational*[T](x: T): Rational[T] = +proc toRational*[T:SomeInteger](x: T): Rational[T] = ## Convert some integer `x` to a rational number. result.num = x result.den = 1 @@ -47,7 +48,7 @@ proc toInt*[T](x: Rational[T]): int = ## `x` does not contain an integer value. x.num div x.den -proc reduce*[T](x: var Rational[T]) = +proc reduce*[T:SomeInteger](x: var Rational[T]) = ## Reduce rational `x`. let common = gcd(x.num, x.den) if x.den > 0: diff --git a/tests/rational/trat_float.nim b/tests/rational/trat_float.nim new file mode 100644 index 000000000..24797c4a0 --- /dev/null +++ b/tests/rational/trat_float.nim @@ -0,0 +1,9 @@ +discard """ + file: "trat_float.nim" + line: "9,19" + errormsg: '''type mismatch: got''' +""" +import rationals +var + # this fails - no floats as num or den + r = initRational(1.0'f, 1.0'f) diff --git a/tests/rational/trat_init.nim b/tests/rational/trat_init.nim new file mode 100644 index 000000000..df29ff6e3 --- /dev/null +++ b/tests/rational/trat_init.nim @@ -0,0 +1,10 @@ +discard """ + file: "trat_init.nim" + exitcode: "1" +""" +import rationals +var + z = Rational[int](num: 0, den: 1) + o = initRational(num=1, den=1) + a = initRational(1, 2) + r = initRational(1, 0) # this fails - no zero denominator |