-
-
Save zeffii/6673006 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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