diff -r 6b8e3d232361 -r 10e7a90d8e7a Fahad/Scala/Chapter6.sc --- a/Fahad/Scala/Chapter6.sc Sat Nov 08 12:19:37 2014 +0000 +++ b/Fahad/Scala/Chapter6.sc Sun Nov 09 19:14:23 2014 +0000 @@ -1,8 +1,9 @@ package greeter - + + object Chapter6 { - println("Classes and Objects") //> Classes and Objects - + println("Classes and Objects") //> Classes and Objects + class Rational(n: Int, d: Int) { private def gcd(x: Int, y: Int): Int = { if (x == 0) y @@ -11,49 +12,49 @@ 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) - + //Inheritance and Overriding override def toString = "" + numer + "/" + denom //Parameterless Methods def square = new Rational(numer * numer, denom * denom) } //Inheritance and Overriding - var i = 1 //> i : Int = 1 - var x = new Rational(0, 1) //> x : greeter.Chapter6.Rational = 0/1 + var i = 1 //> i : Int = 1 + var x = new Rational(0, 1) //> x : greeter.Chapter6.Rational = 0/1 while (i <= 10) { x += new Rational(1, i) i += 1 } - println("" + x.numer + "/" + x.denom) //> 7381/2520 + println("" + x.numer + "/" + x.denom) //> 7381/2520 //Parameterless Methods - val r = new Rational(3, 4) //> r : greeter.Chapter6.Rational = 3/4 - println(r.square) //> 9/16 - + val r = new Rational(3, 4) //> r : greeter.Chapter6.Rational = 3/4 + println(r.square) //> 9/16 + //Abstract Classes abstract class IntSet { def incl(x: Int): IntSet def contains(x: Int): Boolean } - + //Triats trait IntSett { def incl(x: Int): IntSet def contains(x: Int): Boolean } - + //Implementing abstract class class EmptySet extends IntSet { def contains(x: Int): Boolean = false def incl(x: Int): IntSet = new NonEmptySet(x, new EmptySet, new EmptySet) } - + class NonEmptySet(elem: Int, left: IntSet, right: IntSet) extends IntSet { def contains(x: Int): Boolean = if (x < elem) left contains x @@ -64,5 +65,5 @@ else if (x > elem) new NonEmptySet(elem, left, right incl x) else this } - -} \ No newline at end of file + +}