summaryrefslogtreecommitdiffstats
path: root/Scala/sandbox/3-rationals.scala
diff options
context:
space:
mode:
Diffstat (limited to 'Scala/sandbox/3-rationals.scala')
-rw-r--r--Scala/sandbox/3-rationals.scala12
1 files changed, 12 insertions, 0 deletions
diff --git a/Scala/sandbox/3-rationals.scala b/Scala/sandbox/3-rationals.scala
index 3eec82c..868f216 100644
--- a/Scala/sandbox/3-rationals.scala
+++ b/Scala/sandbox/3-rationals.scala
@@ -1,7 +1,14 @@
object Rationals {
+ // primary constuctor
class Rational(x :Int, y: Int) {
+ require(y != 0, "denominator must be non zero") // throws IllegalArgumentException
+ assert(y != 0) // throws AssertionError
+
+ // another constructor
+ def this(x: Int) = this(x, 1)
+
private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
private val g = gcd(x, y)
def numer = x / g
@@ -9,6 +16,10 @@ object Rationals {
def neg = new Rational(-numer, denom)
+ def less(that: Rational) = this.numer * that.denom < that.numer * this.denom
+
+ def max(that: Rational) = if (this.less(that)) that else this
+
def add(that: Rational) =
new Rational(
numer * that.denom + that.numer * denom,
@@ -24,6 +35,7 @@ object Rationals {
println("Rationals")
println(new Rational(2, 3).add(new Rational(3, 4)).toString)
println(new Rational(1, 3).sub(new Rational(5 ,7)).sub(new Rational(3, 2)).toString)
+ println(new Rational(1, 3).max(new Rational(5 ,7)).toString)
}
}