Created
September 17, 2012 06:10
-
-
Save stephenLee/3735803 to your computer and use it in GitHub Desktop.
Scala Rational class to illustrate functional objects
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 number = n / g | |
val denom = d / g | |
def this(n: Int) = this(n, 1) // auxiliary constructor | |
def + (that: Rational): Rational = | |
new Rational( | |
number * that.denom + that.number * denom, | |
denom * that.denom | |
) | |
def + (i: Int): Rational = | |
new Rational(number + i * denom, denom) | |
def - (that: Rational): Rational = | |
new Rational( | |
number * that.denom - that.number * denom, | |
denom * that.denom | |
) | |
def - (i: Int): Rational = | |
new Rational(number - i * denom, denom) | |
def * (that: Rational): Rational = | |
new Rational(number * that.number, denom * that.denom) | |
def * (i: Int): Rational = | |
new Rational(number * i, denom) | |
def / (that: Rational): Rational = | |
new Rational(number * that.denom, denom * that.number) | |
def / (i: Int): Rational = | |
new Rational(number, denom * i) | |
override def toString = number + "/" + denom | |
private def gcd(a: Int, b: Int): Int = | |
if (b == 0) a else gcd(b, a % b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment