Fahad/Scala/Chapter6.sc
author fahadausaf <fahad.ausaf@icloud.com>
Sun, 26 Oct 2014 16:42:28 +0000
changeset 32 fa92e8f089a2
child 43 10e7a90d8e7a
permissions -rw-r--r--
no message

package greeter

object Chapter6 {
  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
      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)

    //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
  while (i <= 10) {
    x += new Rational(1, i)
    i += 1
  }
  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

  //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
      else if (x > elem) right contains x
      else true
    def incl(x: Int): IntSet =
      if (x < elem) new NonEmptySet(elem, left incl x, right)
      else if (x > elem) new NonEmptySet(elem, left, right incl x)
      else this
  }

}