Skip to content

Instantly share code, notes, and snippets.

@wong2 wong2/Rational.scala
Created Oct 22, 2014

Embed
What would you like to do?
"Programming Scala" Chapter 6
class Rational(n: Int, d: Int) {
require(d != 0)
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)
override def toString() = numer + "/" + denom
private def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
def + (that: Rational) =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom
)
def + (i: Int) =
new Rational(numer + i * denom, denom)
def * (that: Rational) =
new Rational(numer * that.numer, denom * that.denom)
def * (i: Int) =
new Rational(numer * i, denom)
def lessThan(that: Rational) =
numer * that.denom < that.numer * denom
def max(that: Rational) =
if (this.lessThan(that)) that else this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.