Advertisement
jules0707

Rational

Feb 27th, 2017
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.86 KB | None | 0 0
  1. package example
  2.  
  3. class Rational(x: Int, y: Int) {
  4.   require(y!=0, "denom cannot be zero")
  5.  
  6.   def this(x:Int) = this (x,1)
  7.    
  8.   private def gcd(a:Int, b:Int):Int = if (b==0) a else gcd(b, a%b)
  9.   private val g = gcd(x,y)
  10.  
  11.   val numer = x
  12.   val denom = y
  13.  
  14.   def < (that:Rational) = numer*that.denom < denom*that.numer
  15.   def max(that: Rational) = if(this < that) that else this
  16.  
  17.   def +(that: Rational) =
  18.     new Rational((numer * that.denom + that.numer * denom), denom * that.denom)
  19.  
  20.   override def toString = numer/g + "/" + denom/g
  21.  
  22.   def unary_- :Rational = new Rational(-numer, denom)
  23.  
  24.   def - (that: Rational) = this + -that
  25.  
  26. }
  27.  
  28. object rationals {
  29.   val k = new Rational(4)
  30.   val x = new Rational(1, 3)
  31.   x.numer
  32.   x.denom
  33.   val y = new Rational(5, 7)
  34.   val z = new Rational(3, 2)
  35.   y < z
  36.   z.toString
  37.   -x
  38.   x - y
  39.   y + y
  40.   x - y - z
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement