Skip to content

Instantly share code, notes, and snippets.

@anujku
Last active May 31, 2016 05:50
Show Gist options
  • Save anujku/c517982f6f413a74bf50d1abc28034a1 to your computer and use it in GitHub Desktop.
Save anujku/c517982f6f413a74bf50d1abc28034a1 to your computer and use it in GitHub Desktop.
Scala Functions and Data
class Rational(x: Int, y: Int) {
require(y != 0, "denominator must be non zero")
def this(x: Int) = this(x, 1)
private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
private val g = gcd(x, y)
def numer = x / g
def denom = y / g
def unary_- : Rational = new Rational(-numer, denom)
def +(that: Rational): Rational = {
new Rational(numer * that.denom + that.numer * denom, denom * that.denom)
}
def -(that: Rational): Rational = this + -that
def <(that: Rational) = numer * that.denom < that.numer * denom
def max(that: Rational) = if (this < that) that else this
override def toString = numer + "/" + denom
}
val rational1 = new Rational(1, 3)
val rational2 = new Rational(5, 7)
val rational3 = new Rational(3, 2)
val rational4 = new Rational(3)
rational1 - rational2 - rational3
rational2 + rational2
rational1 < rational2
rational1 max rational2
-rational4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment