--- a/progs/lecture4.scala Fri Dec 07 12:17:27 2018 +0000
+++ b/progs/lecture4.scala Sun Dec 09 01:36:49 2018 +0000
@@ -209,6 +209,46 @@
+// another example about Fractions
+import scala.language.implicitConversions
+import scala.language.reflectiveCalls
+
+
+case class Fraction(numer: Int, denom: Int) {
+ override def toString = numer.toString + "/" + denom.toString
+
+ def +(other: Fraction) = Fraction(numer + other.numer, denom + other.denom)
+ def /(other: Fraction) = Fraction(numer * other.denom, denom * other.numer)
+ def /% (other: Fraction) = Fraction(numer * other.denom, denom * other.numer)
+
+}
+
+implicit def Int2Fraction(x: Int) = Fraction(x, 1)
+
+
+val half = Fraction(1, 2)
+val third = Fraction (1, 3)
+
+half + third
+half / third
+
+// not sure if one can get this to work
+// properly, since Scala just cannot find out
+// if / is for ints or for Fractions
+(1 / 3) + half
+(1 / 2) + third
+
+// either you have to force the Fraction-type by
+// using a method that is not defined for ints
+(1 /% 3) + half
+(1 /% 2) + third
+
+
+// ...or explicitly give the type in order to allow
+// Scala to do the conversion to Fractions
+((1:Fraction) / 3) + half
+(1 / (3: Fraction)) + half
+
// DFAs in Scala