Skip to content

Instantly share code, notes, and snippets.

@wong2
Created October 22, 2014 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wong2/6fb92aa9ef49507d6feb to your computer and use it in GitHub Desktop.
Save wong2/6fb92aa9ef49507d6feb to your computer and use it in GitHub Desktop.
"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