Skip to content

Instantly share code, notes, and snippets.

@fancellu
Last active August 29, 2015 13:57
Embed
What would you like to do?
Nice OO Scala example for a talk for Harvey Nash
5/3
5/3
1/3
4/9
true
10
true
false
List(2/3, 1, 10/7, 2)
object Rational extends App {
case class Rational(n: Int, d: Int=1) extends Ordered[Rational]{
require(d != 0)
private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d / g
def + (that: Rational) = Rational( numer * that.denom + that.numer * denom, denom * that.denom)
def - (that: Rational) = Rational(numer * that.denom - that.numer * denom, denom * that.denom)
def unary_- = Rational(-numer,denom)
def * (that: Rational) = Rational(numer * that.numer, denom * that.denom)
def / (that: Rational) = Rational(numer * that.denom, denom * that.numer)
override def toString = if (denom==1) numer.toString else numer +"/"+ denom
def compare(that: Rational) = this.numer * that.denom - that.numer * this.denom
def ==(that: Rational) = that.numer == numer && that.denom == denom
def ==(that: Int):Boolean = this == Rational(that)
}
implicit def toRational(num: Int) = Rational(num)
val r2=Rational(2,3)
println(1+r2)
println(r2+1)
println(-r2+1)
println(r2*r2)
println(Rational(10)==Rational(20,2))
println(Rational(10))
println (1>Rational(1,2))
println (1>Rational(3,2))
val list=List[Rational](1,2,Rational(2,3),Rational(10,7))
println(list.sorted)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment