// code examples from Scala by Example, chapter 6, // class Rational(n: Int, d: Int) { private def gcd(x: Int, y: Int): Int = { if (x == 0) y else if (x < 0) gcd(-x,y) else if (y < 0) -gcd(x, -y) else gcd(y % x, x) } private val g = gcd(n, d) val numer: Int = n/g val denom: Int = d/g def +(that: Rational) = new Rational(numer * that.denom + that.numer * denom, denom * that.denom) def -(that: Rational) = new Rational(numer * that.denom - that.numer * denom, denom * that.denom) def *(that: Rational) = new Rational(numer * that.numer, denom * that.denom) def /(that: Rational) = new Rational(numer * that.denom, denom * that.numer) override def toString = "" + numer + "/" + denom + "" def square = new Rational(numer*numer, denom*denom) } def sumOfFractions (max: Int): Rational = { var i = 1 var sum = new Rational(0, 1) while (i <= max) { sum += new Rational(1, i) i += 1 } sum } // can you do a (tail) recursive version of sumOfFractions ? // in Scala, every class extends class "AnyRef" (cf. Object in Java) var x: AnyRef = sumOfFractions(2) // try: x * new Rational(3 ,4 ) // try: x.asInstanceOf[Rational] * new Rational(3 ,4 ) //======================================================================