Skip to content

Instantly share code, notes, and snippets.

@zeffii
Forked from anonymous/Rational.scala
Created September 23, 2013 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeffii/6673006 to your computer and use it in GitHub Desktop.
Save zeffii/6673006 to your computer and use it in GitHub Desktop.
object rationals {
val x = new Rational(1,3) //> x : Rational = 1/3
x.numer //> res0: Int = 1
x.denom //> res1: Int = 3
val y = new Rational(5,7) //> y : Rational = 5/7
x.add(y) //> res2: Rational = 22/21
val z = new Rational(3,2) //> z : Rational = 3/2
//val m = x - y - z
x.neg //> res3: Rational = -1/3
x.sub(y).sub(z) //> res4: Rational = -79/42
}
class Rational(x: Int, y: Int) {
def numer = x
def denom = y
def add(that: Rational) =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom)
//def -(that: Rational) = new Rational(-x, y)
def neg: Rational = new Rational(-numer, denom)
def sub(that: Rational) = add(that.neg)
override def toString = numer + "/" + denom
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment