summaryrefslogtreecommitdiffstats
path: root/Scala
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2013-04-09 22:59:44 +0200
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-10 18:03:22 +0100
commit73df62063a2426d646b335dd42e36068455c77a6 (patch)
tree61ed73c9f63f30e550d081ac6ebc1d9190f08c1d /Scala
parent6bffe17cb037b5c102cfca1dfb75376625784743 (diff)
downloadcoursera-73df62063a2426d646b335dd42e36068455c77a6.zip
coursera-73df62063a2426d646b335dd42e36068455c77a6.tar.gz
Scala : add constructor, method less and max to Rationals
Diffstat (limited to '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)
}
}