updated duration class
authorChristian Urban <christian.urban@kcl.ac.uk>
Mon, 30 Nov 2020 12:58:37 +0000
changeset 381 116fa3c8584f
parent 380 d19b0a50ceb9
child 382 1bd800376e0c
updated duration class
progs/lecture4.scala
--- a/progs/lecture4.scala	Mon Nov 30 03:33:30 2020 +0000
+++ b/progs/lecture4.scala	Mon Nov 30 12:58:37 2020 +0000
@@ -523,7 +523,7 @@
 // Conversions add a wrapper when a member of T is requested 
 // from an instance of C.
 
-//Another example (TimeUnit in 2.13?)
+
 
 import scala.concurrent.duration.{TimeUnit,SECONDS,MINUTES}
 
@@ -533,8 +533,8 @@
 }
 
 implicit class Int2Duration(that: Int) {
-  def seconds = new Duration(that, SECONDS)
-  def minutes = new Duration(that, MINUTES)
+  def seconds = Duration(that, SECONDS)
+  def minutes = Duration(that, MINUTES)
 }
 
 5.seconds + 2.minutes   //Duration(125L, SECONDS )
@@ -574,11 +574,9 @@
 implicit def string2rexp(s: String): Rexp = 
   charlist2rexp(s.toList)
 
-"(a|b)"
+val r1 = STAR("hello")
+val r2 = STAR("hello") | STAR("world")
 
-val r1 = STAR("ab")
-val r2 = (STAR("ab")) | (STAR("ba"))
-val r3 = STAR(SEQ("ab", ALT("a", "b")))
 
 implicit def RexpOps (r: Rexp) = new {
   def | (s: Rexp) = ALT(r, s)
@@ -595,6 +593,8 @@
 }
 
 //example regular expressions
+
+
 val digit = ("0" | "1" | "2" | "3" | "4" | 
               "5" | "6" | "7" | "8" | "9")
 val sign = "+" | "-" | ""
@@ -602,18 +602,29 @@
 
 
 
-// Mind-Blowing Regular Expressions
+
+// In mandelbrot.scala I used complex (imaginary) numbers 
+// and implemented the usual arithmetic operations for complex 
+// numbers.
 
-// same examples using the internal regexes
-val evil = "(a*)*b"
+case class Complex(re: Double, im: Double) { 
+  // represents the complex number re + im * i
+  def +(that: Complex) = Complex(this.re + that.re, this.im + that.im)
+  def -(that: Complex) = Complex(this.re - that.re, this.im - that.im)
+  def *(that: Complex) = Complex(this.re * that.re - this.im * that.im,
+                                 this.re * that.im + that.re * this.im)
+  def *(that: Double) = Complex(this.re * that, this.im * that)
+  def abs = Math.sqrt(this.re * this.re + this.im * this.im)
+}
+
+val test = Complex(1, 2) + Complex (3, 4)
 
 
-println("a" * 100)
+// ...to allow the notation n + m * i
+import scala.language.implicitConversions   
 
-("a" * 10000).matches(evil)
-("a" * 10).matches(evil)
-("a" * 10000).matches(evil)
-("a" * 20000).matches(evil)
-("a" * 50000).matches(evil)
+val i = Complex(0, 1)
+implicit def double2complex(re: Double) = Complex(re, 0)
 
-time_needed(1, ("a" * 50000).matches(evil))
+val inum1 = -2.0 + -1.5 * i
+val inum2 =  1.0 +  1.5 * i