DEV Community

Discussion on: The day I almost made a library on a bakery

Collapse
 
evanoman profile image
Evan Oman • Edited

I thought I had implemented Rational before, here is my quick implementation for this Stack Overflow question:

scala> :pa
// Entering paste mode (ctrl-D to finish)

object Rational
{
    def apply(n: BigInt, d: BigInt): Rational =
    {
        val neg_mod = if (d < BigInt(0)) BigInt(-1) else BigInt(1)
        val (n_mod, d_mod) = (neg_mod * n, neg_mod * d)
        val gcd_val = gcd(n_mod, d_mod)
        new Rational(n_mod / gcd_val, d_mod / gcd_val)
    }
    def gcd(a: BigInt, b: BigInt): BigInt = if (b == BigInt(0)) a else gcd(b, a % b)
}
class Rational(val n: BigInt, val d: BigInt)
{
    override def toString: String = if (n == BigInt(0)) "0" else if (d == BigInt(1)) s"$n" else s"$n/$d"

    def toDouble: Double = n.toDouble / d.toDouble

    def *(that: Rational): Rational = Rational(n * that.n, d * that.d)

    def /(that: Rational): Rational = Rational(n * that.d, d * that.n)

    def +(that: Rational): Rational = Rational(n * that.d + that.n * d, d * that.d)

    def -(that: Rational): Rational = this + (-that)

    def unary_- = Rational(-n, d)
}

// Exiting paste mode, now interpreting.

defined object Rational
defined class Rational

scala> val a = Rational(60075, 10000)
a: Rational = 2403/400

scala> val b = Rational(1, 1)
b: Rational = 1

scala> val c = Rational(89, 100)
c: Rational = 89/100

scala> a * (b / c)
res0: Rational = 27/4

scala> (a * (b / c)).toDouble
res1: Double = 6.75
Collapse
 
ben profile image
Ben Halpern

Nice