summaryrefslogtreecommitdiffstats
path: root/Scala/sandbox/3-rationals.scala
blob: d1eda221b1e6b6fb30bb2ac5d488e1f2b0be5c8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

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
    def denom = y / g

    def unary_- = new Rational(-numer, denom)

    def < (that: Rational) = this.numer * that.denom < that.numer * this.denom

    def max(that: Rational) = if (this < (that)) that else this

    def + (that: Rational) =
      new Rational(
        numer * that.denom + that.numer * denom,
        denom * that.denom)

    def - (that: Rational) = this + -that

    override def toString = numer + "/" + denom

  }

  def run = {
    println("Rationals")
    println(new Rational(2, 3) + (new Rational(3, 4)) toString)
    println(new Rational(1, 3) - (new Rational(5 ,7)) - (new Rational(3, 2)) toString)
    println(new Rational(1, 3) max (new Rational(5 ,7)) toString)
  }

}