Skip to content

Instantly share code, notes, and snippets.

@ajjain
Last active December 28, 2015 20:29
Show Gist options
  • Save ajjain/7557269 to your computer and use it in GitHub Desktop.
Save ajjain/7557269 to your computer and use it in GitHub Desktop.
Datastructures in Scala
package learn.scala
/**
* Datastructures in Scala
* The example below shows abstracting Rational numbers and implementing
* rational number arithmetics.
*
* Similar to java scala does provide toString for printing the datastructure representation.
* In the example below we override toString method. Also, we make use of this construct which
* is also available in Scala.
* Introduction to the access modifiers here GCD for example
* pre checks using require function
*/
class Rational(x: Int, y: Int) {
// represents a check on denominator
require(y != 0, "Denominator must be a non zero")
// private GCD definition abstracted from client
private def gcd(x: Int, y: Int): Int = if (y==0) x else gcd(y, x % y)
// another constructor other than default expressed in the definition to support integers
// all integers are rational with denominator as 1
def this(x: Int) = this(x, 1)
def numerator = x
def denominator = y
def sum ( rational: Rational): Rational = {
val newNumer = (this.numerator * rational.denominator) + (this.denominator * rational.numerator)
val newDenom = this.denominator * rational.denominator
val result = new Rational(newNumer, newDenom)
result
}
def less(that: Rational): Boolean = this.numerator * that.denominator < that.numerator * this.denominator
override def toString = (this.numerator / gcd(this.numerator, this.denominator)) + "/" + (this.denominator / gcd(this.numerator, this.denominator))
}
object DataStructureExample {
val rational = new Rational (1, 2) //> rational : learn.scala.Rational = 1/2
rational.numerator //> res0: Int = 1
rational.denominator //> res1: Int = 2
// ---------------- adding two rational number ------------------
val rational1 = new Rational(5,6) //> rational1 : learn.scala.Rational = 5/6
val rational2 = rational.sum(rational1) //> rational2 : learn.scala.Rational = 4/3
rational2.numerator //> res2: Int = 16
rational2.denominator //> res3: Int = 12
rational1.less(rational2) //> res4: Boolean = true
println(rational2) //> 4/3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment