progs/lecture4.scala
changeset 243 9bb36426c781
parent 242 e6b34f617915
child 278 0c2481cd8b1c
equal deleted inserted replaced
242:e6b34f617915 243:9bb36426c781
   206 
   206 
   207 // BUT since we are completely IMMUTABLE, this is 
   207 // BUT since we are completely IMMUTABLE, this is 
   208 // virtually of not concern to us.
   208 // virtually of not concern to us.
   209 
   209 
   210 
   210 
       
   211 
       
   212 // another example about Fractions
       
   213 import scala.language.implicitConversions
       
   214 import scala.language.reflectiveCalls
       
   215 
       
   216 
       
   217 case class Fraction(numer: Int, denom: Int) {
       
   218   override def toString = numer.toString + "/" + denom.toString
       
   219 
       
   220   def +(other: Fraction) = Fraction(numer + other.numer, denom + other.denom)
       
   221   def /(other: Fraction) = Fraction(numer * other.denom, denom * other.numer)
       
   222   def /% (other: Fraction) = Fraction(numer * other.denom, denom * other.numer)
       
   223 
       
   224 }
       
   225 
       
   226 implicit def Int2Fraction(x: Int) = Fraction(x, 1)
       
   227 
       
   228 
       
   229 val half = Fraction(1, 2)
       
   230 val third = Fraction (1, 3)
       
   231 
       
   232 half + third
       
   233 half / third
       
   234 
       
   235 // not sure if one can get this to work
       
   236 // properly, since Scala just cannot find out
       
   237 // if / is for ints or for Fractions 
       
   238 (1 / 3) + half
       
   239 (1 / 2) + third
       
   240 
       
   241 // either you have to force the Fraction-type by
       
   242 // using a method that is not defined for ints
       
   243 (1 /% 3) + half
       
   244 (1 /% 2) + third
       
   245 
       
   246 
       
   247 // ...or explicitly give the type in order to allow
       
   248 // Scala to do the conversion to Fractions 
       
   249 ((1:Fraction) / 3) + half
       
   250 (1 / (3: Fraction)) + half
   211 
   251 
   212 
   252 
   213 
   253 
   214 // DFAs in Scala  
   254 // DFAs in Scala  
   215 //===============
   255 //===============