Skip to content

Instantly share code, notes, and snippets.

@stephenLee
Created September 17, 2012 06:10
Show Gist options
  • Save stephenLee/3735803 to your computer and use it in GitHub Desktop.
Save stephenLee/3735803 to your computer and use it in GitHub Desktop.
Scala Rational class to illustrate functional objects
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