Esimerkki
[Scala
by Example]:
class Rational(n: Int, d: Int) {
private def gcd(x: Int, y: Int): Int = {
if (x == 0) y
else if (x < 0) gcd(-x, y)
else if (y < 0) gcd(x, -y)
else gcd(y % x, x)
}
private val g = gcd(n, d)
val numer: Int = n/g
val denom: Int = d/g
def +(that: Rational) =
new Rational(numer * that.denom + that.numer * denom,
denom * that.denom)
def -(that: Rational) =
new Rational(numer * that.denom - that.numer * denom,
denom * that.denom)
def *(that: Rational) =
new Rational(numer * that.numer, denom * that.denom)
def /(that: Rational) =
new Rational(numer * that.denom, denom * that.numer)
override def toString() = "(" + numer + "/" + denom +")" // oma lisäys
// korjattu 21.10.2008!
}
//--- pää ------------------ oma lisäys
object ratio {
def main(args: Array[String]) = {
val a = new Rational(2,3)
val b = new Rational(1,4)
println(a+b)
println(a-b)
println(a*b)
println(a/b)
}
}
Ohjelma tulostaa:
(11/12)
(5/12)
(1/6)
(8/3)