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:
parent
d6b7f0ad9e
commit
2f4cc4efce
1 changed files with 3 additions and 3 deletions
|
|
@ -18,7 +18,7 @@ type Rational*[T] = object
|
||||||
## a rational number, consisting of a numerator and denominator
|
## a rational number, consisting of a numerator and denominator
|
||||||
num*, den*: T
|
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.
|
## Create a new rational number.
|
||||||
assert(den != 0, "a denominator of zero value is invalid")
|
assert(den != 0, "a denominator of zero value is invalid")
|
||||||
result.num = num
|
result.num = num
|
||||||
|
|
@ -34,7 +34,7 @@ proc `$`*[T](x: Rational[T]): string =
|
||||||
## Turn a rational number into a string.
|
## Turn a rational number into a string.
|
||||||
result = $x.num & "/" & $x.den
|
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.
|
## Convert some integer `x` to a rational number.
|
||||||
result.num = x
|
result.num = x
|
||||||
result.den = 1
|
result.den = 1
|
||||||
|
|
@ -48,7 +48,7 @@ proc toInt*[T](x: Rational[T]): int =
|
||||||
## `x` does not contain an integer value.
|
## `x` does not contain an integer value.
|
||||||
x.num div x.den
|
x.num div x.den
|
||||||
|
|
||||||
proc reduce*[T](x: var Rational[T]) =
|
proc reduce*[T:SomeInteger](x: var Rational[T]) =
|
||||||
## Reduce rational `x`.
|
## Reduce rational `x`.
|
||||||
let common = gcd(x.num, x.den)
|
let common = gcd(x.num, x.den)
|
||||||
if x.den > 0:
|
if x.den > 0:
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue