Created
October 22, 2014 10:02
-
-
Save wong2/6fb92aa9ef49507d6feb to your computer and use it in GitHub Desktop.
"Programming Scala" Chapter 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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