Created
October 17, 2016 21:30
-
-
Save albertywu/0c9ddf67cd1b7c2652cfe41534f770ad to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class Rational(x: Int, y: Int) { | |
| // private method | |
| private def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y) | |
| // private value | |
| private val g = gcd(x, y) | |
| // accessor methods | |
| def numer = x / g // normalize using gcd | |
| def denom = y / g // normalize using gcd | |
| // methods can be used as infix operators | |
| // e.g. r1 < r2 will rewrite to r1.<(r2) | |
| def < (that: Rational) = numer * that.denom < that.numer * denom | |
| // addition | |
| def + (that: Rational) = new Rational( | |
| numer * that.denom + that.numer * denom, | |
| denom * that.denom | |
| ) | |
| // symbolic prefix operators | |
| // use <unary_><symbol> | |
| def unary_- : Rational = new Rational(-numer, denom) | |
| // subtraction | |
| def - (that: Rational) = this + -that | |
| // override modifier needed here | |
| override def toString = numer + "/" + denom | |
| } | |
| val r1 = new Rational(1,2) | |
| val r2 = new Rational(1,3) | |
| println( | |
| r1, | |
| r2, | |
| -r1, | |
| -r2, | |
| r1 < r2, | |
| r2 < r1, | |
| r1 + r2, | |
| r1 - r2 | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment