Skip to content

Instantly share code, notes, and snippets.

@megri
Last active June 12, 2017 15:40
Show Gist options
  • Save megri/4b07239d69dd2b66ccac9fbb601f16ee to your computer and use it in GitHub Desktop.
Save megri/4b07239d69dd2b66ccac9fbb601f16ee to your computer and use it in GitHub Desktop.
object Rational {
implicit def rationalInt(n: Int): Rational =
Rational(n, 1)
def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
}
case class Rational(p: Int, q: Int) {
require(q != 0, "Denominator 'q' cannot be 0")
def + (that: Rational) =
Rational(
this.p * that.q + that.p * this.q,
this.q * that.q
)
def - (that: Rational) =
Rational(
this.p * that.q - that.p * this.q,
this.q * that.q
)
def * (that: Rational) =
Rational(
this.p * that.p,
this.q * that.q
)
def / (that: Rational) =
Rational(
this.p * that.q,
this.q * that.p
)
def normalized: Rational = {
val gcd = Rational.gcd(p, q)
val lcm = p * q / gcd
Rational(p / gcd, q / gcd)
}
}
val r1 = Rational(1,5) + Rational(6,4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment