mirror of
https://github.com/nim-lang/Nim.git
synced 2026-04-19 14:00:35 +00:00
Merge pull request #3406 from jlp765/rationals1
Rationals - add checks and tests
This commit is contained in:
@@ -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:
|
||||
|
||||
9
tests/rational/trat_float.nim
Normal file
9
tests/rational/trat_float.nim
Normal file
@@ -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)
|
||||
10
tests/rational/trat_init.nim
Normal file
10
tests/rational/trat_init.nim
Normal file
@@ -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
|
||||
Reference in New Issue
Block a user