Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package example
- class Rational(x: Int, y: Int) {
- require(y!=0, "denom cannot be 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)
- val numer = x
- val denom = y
- def < (that:Rational) = numer*that.denom < denom*that.numer
- def max(that: Rational) = if(this < that) that else this
- def +(that: Rational) =
- new Rational((numer * that.denom + that.numer * denom), denom * that.denom)
- override def toString = numer/g + "/" + denom/g
- def unary_- :Rational = new Rational(-numer, denom)
- def - (that: Rational) = this + -that
- }
- object rationals {
- val k = new Rational(4)
- val x = new Rational(1, 3)
- x.numer
- x.denom
- val y = new Rational(5, 7)
- val z = new Rational(3, 2)
- y < z
- z.toString
- -x
- x - y
- y + y
- x - y - z
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement