mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-29 01:14:41 +00:00
add a few type checks to limit type to SomeInteger
(adding a compund type to the Rational type definition made it too difficult to define new variables using integer literals)
This commit is contained in:
@@ -18,7 +18,7 @@ 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
|
||||
@@ -34,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
|
||||
@@ -48,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:
|
||||
|
||||
Reference in New Issue
Block a user