// See scala/books/examples/functional-objects/ex9
// See http://d.hatena.ne.jp/zetta1985/20091127/1259333184
// See http://gist.github.com/liesen/scala-kata-util/blob/ac1007c2f017a7914e60b097743f5318e85ea792/src/util/Rational.scala

package rational

class Rational0(n: Int, d: Int) {

    require(d != 0)

    private val g = gcd(n.abs, d.abs)
    val numer = n / g
    val denom = d / g

    def this(n: Int) = this(n, 1)

    def + (that: Rational0): Rational0 = {
        new Rational0(
            numer * that.denom + that.numer * denom,
              denom * that.denom
        )
    }

    def - (that: Rational0): Rational0 = {
        new Rational0(
            numer * that.denom - that.numer * denom,
              denom * that.denom
        )
    }

    def * (that: Rational0): Rational0 = {
        new Rational0(numer * that.numer, denom * that.denom)
    }

    def / (that: Rational0): Rational0 = {
        new Rational0(numer * that.denom, denom * that.numer)
    }

    override def toString = numer +"/"+ denom

    private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
}

object MainX {
    def main(args: Array[String]) {
        val x = new Rational0(1, 2)
        val y = new Rational0(2, 3)
        println("x [" + x + "]")
        println("y [" + y + "]")
        println("x + y [" + (x + y) + "]")
        println("x.+(y) [" + (x.+(y)) + "]")
        println("x + x * y [" + (x + x * y) + "]")
        println("(x + x) * y [" + ((x + x) * y) + "]")
        println("x + (x * y) [" + (x + (x * y)) + "]")

        println("x - y [" + (x - y ) + "]")
        println("x / y [" + (x / y ) + "]")
    }
}