This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
ProgrammingInScala/Chapter6/src/main/Rational.scala

39 lines
1.4 KiB
Scala

package main
/**
* Created by claudio on 02/10/16.
*/
class Rational(n: Int, d: Int) {
require(d!=0) //throw IllegalArgumentException if not
private val g = gcd(n.abs,d.abs)
val numer: Int = n / g
val denom: Int = d / g
def this(n: Int) = this(n, 1) //Auxiliary constructors MUST call another construct
override def toString = if (d == 1) s"$n" else s"$n/$d"
def +(that: Rational): Rational = new Rational((numer * that.denom) +
(that.numer * denom), denom * that.denom)
def +(that: Int): Rational = new Rational(numer + that * denom, denom)
def -(that: Rational): Rational = this + new Rational(-that.numer, denom)
def -(that: Int): Rational = this + -that
def *(that: Rational): Rational = new Rational(numer * that.numer, denom * that.denom)
def *(that: Int): Rational = new Rational(numer * that, denom)
def /(that: Rational): Rational = this * that.reciprocal
def /(that: Int): Rational = this * new Rational(1, that)
def reciprocal: Rational = new Rational(denom, numer)
def lessThan(that: Rational): Boolean = numer * that.denom < that.numer * denom
def max(that: Rational): Rational = if (this lessThan that) that else this
private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
implicit def IntToRational(x: Int): Rational = new Rational(x)
}
object Rational{
def apply(numer: Int): Rational = new Rational(numer)
def apply(numer: Int, denom: Int): Rational = new Rational(numer, denom)
}