June 24, 2010

class Rational from Programming in Scala

A specification for class Rational from Programming in Scala

package funobject

/** Rational number is a number that can be expressed as ratio of n/d,
 * where n and d are integers, except that d can not be zero.
 */

class Rational(n: Int, d: Int) extends Ordered[Rational] {
  require(d != 0)

  private val g = gcd(n.abs, d.abs)
  val nomer = (if (d < 0) -n else n) / g
  val denom = d.abs / g

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


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

  def + (that: Rational):Rational =
    new Rational (nomer * that.denom + that.nomer * denom,
                  denom * that.denom)
  def - (that: Rational):Rational =  -this + that

  def * (that: Rational):Rational =
    new Rational (nomer * that.nomer,
                  denom * that.denom)
  def / (that: Rational):Rational =
    new Rational (nomer * that.denom,
                  denom * that.nomer)

  override def equals (other: Any): Boolean = other match { 
    case that: Rational => this.nomer == that.nomer &&
                           this.denom == that.denom
    case _ => false

  }

  override def compare(that: Rational) = 
    this.nomer * that.denom - that.nomer * this.denom

  override def compareTo(that: Rational) = this.compare(that)

  override def <= (that: Rational): Boolean = compare(that) <= 0
  override def >= (that: Rational): Boolean = compare(that) >= 0
  override def <  (that: Rational): Boolean = compare(that) <  0
  override def >  (that: Rational): Boolean = compare(that) > 0


  override def toString = nomer + "/" + denom

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

object Rational {
  implicit def implicitRationalFromInt(i: Int): Rational = new Rational(i)
  def apply(n: Int, d: Int) = new Rational(n, d)
  def apply(n: Int) = new Rational(n)
}


No comments:

Post a Comment