Skip to content

Instantly share code, notes, and snippets.

@nicola88
Created July 11, 2019 08:45
Show Gist options
  • Select an option

  • Save nicola88/8ee2a5c3db3bac1d375b5d1a0d74adb8 to your computer and use it in GitHub Desktop.

Select an option

Save nicola88/8ee2a5c3db3bac1d375b5d1a0d74adb8 to your computer and use it in GitHub Desktop.
Programming in Scala #book
class Rational(n: Int, d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d / g
def this(n: Int) = this(n, 1)
override def toString = s"$numer/$denom"
def + (that: Rational): Rational =
new Rational(numer * that.denom + that.numer * denom, denom * that.denom)
def + (i: Int): Rational =
new Rational(numer + i * denom, denom)
def - (that: Rational): Rational =
new Rational(numer * that.denom - that.numer * denom, denom * that.denom)
def - (i: Int): Rational =
new Rational(numer - i * denom, denom)
def * (that: Rational): Rational =
new Rational(numer * that.numer, denom * that.denom)
def * (i: Int): Rational =
new Rational(numer * i, denom)
def / (that: Rational): Rational =
new Rational(numer * that.denom, denom * that.numer)
def / (i: Int): Rational =
new Rational(numer, denom * i)
def lessThan(that: Rational) = numer * that.denom < that.numer * denom
def max(that: Rational) = if (lessThan(that)) that else this
private def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
}
implicit def intToRational(x: Int): Rational = new Rational(x)
val r1 = new Rational(1, 2)
val r2 = new Rational(2, 3)
val r3 = new Rational(5)
r1 + r2
r1 + 2
2 + r1
r1 - r2
r1 - 2
r1 * r2
r1 * 2
2 * r1
r1 / r2
r1 / 2
r1 lessThan r2
r2 lessThan r1
r2 max r3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment