| author | Christian Urban <christian.urban@kcl.ac.uk> | 
| Fri, 02 Dec 2022 07:48:03 +0000 | |
| changeset 446 | 30b8f14b2655 | 
| parent 415 | 368556c8df56 | 
| child 447 | 0cf1b374e146 | 
| permissions | -rw-r--r-- | 
| 222 | 1 | // Scala Lecture 4 | 
| 2 | //================= | |
| 3 | ||
| 415 | 4 | // tail-recursion | 
| 5 | // polymorphic types | |
| 6 | // implicits | |
| 7 | ||
| 8 | import scala.annotation.tailrec | |
| 9 | ||
| 10 | def fact(n: BigInt): BigInt = | |
| 11 | if (n == 0) 1 else n * fact(n - 1) | |
| 12 | ||
| 446 | 13 | |
| 415 | 14 | def factT(n: BigInt, acc: BigInt): BigInt = | 
| 15 | if (n == 0) acc else factT(n - 1, n * acc) | |
| 16 | ||
| 17 | ||
| 18 | println(factT(1000000), 1)) | |
| 19 | ||
| 20 | ||
| 21 | def foo[A](args: List[A]) = ??? | |
| 22 | ||
| 23 | foo(List("1","2","3","4"))
 | |
| 24 | ||
| 25 | ||
| 26 | // from knight1.scala | |
| 27 | def first(xs: List[Pos], f: Pos => Option[Path]) : Option[Path] = ??? | |
| 28 | ||
| 29 | // should be | |
| 30 | def first[A, B](xs: List[A], f: A => Option[B]) : Option[B] = ??? | |
| 31 | ||
| 222 | 32 | |
| 325 | 33 | // expressions (essentially trees) | 
| 34 | ||
| 35 | abstract class Exp | |
| 36 | case class N(n: Int) extends Exp // for numbers | |
| 37 | case class Plus(e1: Exp, e2: Exp) extends Exp | |
| 38 | case class Times(e1: Exp, e2: Exp) extends Exp | |
| 39 | ||
| 40 | def string(e: Exp) : String = e match {
 | |
| 41 | case N(n) => s"$n" | |
| 42 |   case Plus(e1, e2) => s"(${string(e1)} + ${string(e2)})" 
 | |
| 43 |   case Times(e1, e2) => s"(${string(e1)} * ${string(e2)})"
 | |
| 44 | } | |
| 45 | ||
| 46 | val e = Plus(N(9), Times(N(3), N(4))) | |
| 47 | println(string(e)) | |
| 48 | ||
| 49 | def eval(e: Exp) : Int = e match {
 | |
| 50 | case N(n) => n | |
| 51 | case Plus(e1, e2) => eval(e1) + eval(e2) | |
| 52 | case Times(e1, e2) => eval(e1) * eval(e2) | |
| 53 | } | |
| 54 | ||
| 55 | println(eval(e)) | |
| 56 | ||
| 57 | // simplification rules: | |
| 58 | // e + 0, 0 + e => e | |
| 59 | // e * 0, 0 * e => 0 | |
| 60 | // e * 1, 1 * e => e | |
| 326 | 61 | // | 
| 62 | // (....0 ....) | |
| 325 | 63 | |
| 64 | def simp(e: Exp) : Exp = e match {
 | |
| 65 | case N(n) => N(n) | |
| 66 |   case Plus(e1, e2) => (simp(e1), simp(e2)) match {
 | |
| 67 | case (N(0), e2s) => e2s | |
| 68 | case (e1s, N(0)) => e1s | |
| 69 | case (e1s, e2s) => Plus(e1s, e2s) | |
| 70 | } | |
| 71 |   case Times(e1, e2) => (simp(e1), simp(e2)) match {
 | |
| 72 | case (N(0), _) => N(0) | |
| 73 | case (_, N(0)) => N(0) | |
| 74 | case (N(1), e2s) => e2s | |
| 75 | case (e1s, N(1)) => e1s | |
| 76 | case (e1s, e2s) => Times(e1s, e2s) | |
| 77 | } | |
| 78 | } | |
| 79 | ||
| 80 | ||
| 81 | val e2 = Times(Plus(N(0), N(1)), Plus(N(0), N(9))) | |
| 82 | println(string(e2)) | |
| 83 | println(string(simp(e2))) | |
| 84 | ||
| 85 | ||
| 86 | // Tokens and Reverse Polish Notation | |
| 87 | abstract class Token | |
| 88 | case class T(n: Int) extends Token | |
| 89 | case object PL extends Token | |
| 90 | case object TI extends Token | |
| 91 | ||
| 92 | // transfroming an Exp into a list of tokens | |
| 93 | def rp(e: Exp) : List[Token] = e match {
 | |
| 94 | case N(n) => List(T(n)) | |
| 95 | case Plus(e1, e2) => rp(e1) ::: rp(e2) ::: List(PL) | |
| 96 | case Times(e1, e2) => rp(e1) ::: rp(e2) ::: List(TI) | |
| 97 | } | |
| 98 | println(string(e2)) | |
| 99 | println(rp(e2)) | |
| 100 | ||
| 326 | 101 | def comp(ls: List[Token], st: List[Int] = Nil) : Int = (ls, st) match {
 | 
| 325 | 102 | case (Nil, st) => st.head | 
| 103 | case (T(n)::rest, st) => comp(rest, n::st) | |
| 104 | case (PL::rest, n1::n2::st) => comp(rest, n1 + n2::st) | |
| 105 | case (TI::rest, n1::n2::st) => comp(rest, n1 * n2::st) | |
| 106 | } | |
| 107 | ||
| 326 | 108 | comp(rp(e)) | 
| 325 | 109 | |
| 110 | def proc(s: String) : Token = s match {
 | |
| 111 | case "+" => PL | |
| 112 | case "*" => TI | |
| 113 | case _ => T(s.toInt) | |
| 114 | } | |
| 115 | ||
| 116 | comp("1 2 + 4 * 5 + 3 +".split(" ").toList.map(proc), Nil)
 | |
| 117 | ||
| 118 | ||
| 380 | 119 | // Polymorphic Types | 
| 120 | //=================== | |
| 121 | ||
| 122 | // You do not want to write functions like contains, first, | |
| 123 | // length and so on for every type of lists. | |
| 124 | ||
| 125 | def length_int_list(lst: List[Int]): Int = lst match {
 | |
| 126 | case Nil => 0 | |
| 127 | case x::xs => 1 + length_int_list(xs) | |
| 128 | } | |
| 129 | ||
| 130 | length_int_list(List(1, 2, 3, 4)) | |
| 131 | ||
| 132 | def length_string_list(lst: List[String]): Int = lst match {
 | |
| 133 | case Nil => 0 | |
| 134 | case _::xs => 1 + length_string_list(xs) | |
| 135 | } | |
| 136 | ||
| 137 | length_string_list(List("1", "2", "3", "4"))
 | |
| 138 | ||
| 139 | ||
| 140 | // you can make the function parametric in type(s) | |
| 141 | ||
| 142 | def length[A](lst: List[A]): Int = lst match {
 | |
| 143 | case Nil => 0 | |
| 144 | case x::xs => 1 + length(xs) | |
| 145 | } | |
| 146 | length(List("1", "2", "3", "4"))
 | |
| 147 | length(List(1, 2, 3, 4)) | |
| 148 | ||
| 149 | length[Int](List(1, 2, 3, 4)) | |
| 150 | ||
| 151 | ||
| 152 | def map[A, B](lst: List[A], f: A => B): List[B] = lst match {
 | |
| 153 | case Nil => Nil | |
| 154 | case x::xs => f(x)::map(xs, f) | |
| 155 | } | |
| 156 | ||
| 157 | map(List(1, 2, 3, 4), (x: Int) => x.toString) | |
| 158 | ||
| 159 | ||
| 160 | // from knight1.scala | |
| 161 | def first(xs: List[Pos], f: Pos => Option[Path]) : Option[Path] = ??? | |
| 162 | ||
| 163 | // should be | |
| 164 | def first[A, B](xs: List[A], f: A => Option[B]) : Option[B] = ??? | |
| 165 | ||
| 166 | // Type inference is local in Scala | |
| 167 | ||
| 168 | def id[T](x: T) : T = x | |
| 169 | ||
| 170 | val x = id(322) // Int | |
| 171 | val y = id("hey")        // String
 | |
| 172 | val z = id(Set(1,2,3,4)) // Set[Int] | |
| 173 | ||
| 174 | ||
| 175 | // The type variable concept in Scala can get really complicated. | |
| 176 | // | |
| 177 | // - variance (OO) | |
| 178 | // - bounds (subtyping) | |
| 179 | // - quantification | |
| 180 | ||
| 181 | // Java has issues with this too: Java allows | |
| 182 | // to write the following incorrect code, and | |
| 183 | // only recovers by raising an exception | |
| 184 | // at runtime. | |
| 185 | ||
| 186 | // Object[] arr = new Integer[10]; | |
| 187 | // arr[0] = "Hello World"; | |
| 188 | ||
| 189 | ||
| 190 | // Scala gives you a compile-time error, which | |
| 191 | // is much better. | |
| 192 | ||
| 193 | var arr = Array[Int]() | |
| 194 | arr(0) = "Hello World" | |
| 195 | ||
| 196 | ||
| 197 | ||
| 198 | ||
| 199 | // Function definitions again | |
| 200 | //============================ | |
| 201 | ||
| 202 | // variable arguments | |
| 203 | ||
| 204 | def printAll(strings: String*) = {
 | |
| 205 | strings.foreach(println) | |
| 206 | } | |
| 207 | ||
| 208 | printAll() | |
| 209 | printAll("foo")
 | |
| 210 | printAll("foo", "bar")
 | |
| 211 | printAll("foo", "bar", "baz")
 | |
| 212 | ||
| 213 | // pass a list to the varargs field | |
| 214 | val fruits = List("apple", "banana", "cherry")
 | |
| 215 | ||
| 216 | printAll(fruits: _*) | |
| 217 | ||
| 218 | ||
| 219 | // you can also implement your own string interpolations | |
| 220 | import scala.language.implicitConversions | |
| 221 | import scala.language.reflectiveCalls | |
| 222 | ||
| 223 | implicit def sring_inters(sc: StringContext) = new {
 | |
| 224 |     def i(args: Any*): String = s"${sc.s(args:_*)}\n"
 | |
| 225 | } | |
| 226 | ||
| 227 | i"add ${3+2} ${3 * 3}" 
 | |
| 228 | ||
| 229 | ||
| 230 | // default arguments | |
| 231 | ||
| 232 | def length[A](xs: List[A]) : Int = xs match {
 | |
| 233 | case Nil => 0 | |
| 234 | case _ :: tail => 1 + length(tail) | |
| 235 | } | |
| 236 | ||
| 237 | def lengthT[A](xs: List[A], acc : Int = 0) : Int = xs match {
 | |
| 238 | case Nil => acc | |
| 239 | case _ :: tail => lengthT(tail, 1 + acc) | |
| 240 | } | |
| 241 | ||
| 242 | lengthT(List.fill(100000)(1)) | |
| 243 | ||
| 244 | ||
| 245 | def fact(n: BigInt, acc: BigInt = 1): BigInt = | |
| 246 | if (n == 0) acc else fact(n - 1, n * acc) | |
| 247 | ||
| 248 | fact(10) | |
| 249 | ||
| 250 | ||
| 251 | ||
| 252 | // currying (Haskell Curry) | |
| 253 | ||
| 254 | def add(x: Int, y: Int) = x + y | |
| 255 | ||
| 256 | List(1,2,3,4,5).map(x => add(3, x)) | |
| 257 | ||
| 258 | def add2(x: Int)(y: Int) = x + y | |
| 259 | ||
| 260 | List(1,2,3,4,5).map(add2(3)) | |
| 261 | ||
| 262 | val a3 : Int => Int = add2(3) | |
| 263 | ||
| 264 | // currying helps sometimes with type inference | |
| 265 | ||
| 266 | def find[A](xs: List[A])(pred: A => Boolean): Option[A] = {
 | |
| 267 |   xs match {
 | |
| 268 | case Nil => None | |
| 269 | case hd :: tl => | |
| 270 | if (pred(hd)) Some(hd) else find(tl)(pred) | |
| 271 | } | |
| 272 | } | |
| 273 | ||
| 274 | find(List(1, 2, 3))(x => x % 2 == 0) | |
| 275 | ||
| 276 | // Source.fromURL(url)(encoding) | |
| 277 | // Source.fromFile(name)(encoding) | |
| 325 | 278 | |
| 279 | ||
| 384 | 280 | // Tail recursion | 
| 281 | //================ | |
| 282 | ||
| 283 | def fact(n: BigInt): BigInt = | |
| 284 | if (n == 0) 1 else n * fact(n - 1) | |
| 285 | ||
| 286 | ||
| 287 | fact(10) | |
| 288 | fact(1000) | |
| 289 | fact(100000) | |
| 290 | ||
| 291 | def factB(n: BigInt): BigInt = | |
| 292 | if (n == 0) 1 else n * factB(n - 1) | |
| 293 | ||
| 294 | def factT(n: BigInt, acc: BigInt): BigInt = | |
| 295 | if (n == 0) acc else factT(n - 1, n * acc) | |
| 296 | ||
| 297 | ||
| 298 | factB(1000) | |
| 299 | ||
| 300 | ||
| 301 | factT(10, 1) | |
| 302 | println(factT(500000, 1)) | |
| 303 | ||
| 304 | ||
| 305 | // there is a flag for ensuring a function is tail recursive | |
| 306 | import scala.annotation.tailrec | |
| 307 | ||
| 308 | @tailrec | |
| 309 | def factT(n: BigInt, acc: BigInt): BigInt = | |
| 310 | if (n == 0) acc else factT(n - 1, n * acc) | |
| 311 | ||
| 312 | factT(100000, 1) | |
| 313 | ||
| 314 | // for tail-recursive functions the Scala compiler | |
| 315 | // generates loop-like code, which does not need | |
| 316 | // to allocate stack-space in each recursive | |
| 317 | // call; Scala can do this only for tail-recursive | |
| 318 | // functions | |
| 319 | ||
| 320 | // Moral: Whenever a recursive function is resource-critical | |
| 321 | // (i.e. works with a large recursion depth), then you need to | |
| 322 | // write it in tail-recursive fashion. | |
| 323 | // | |
| 324 | // Unfortuantely, Scala because of current limitations in | |
| 325 | // the JVM is not as clever as other functional languages. It can | |
| 326 | // only optimise "self-tail calls". This excludes the cases of | |
| 327 | // multiple functions making tail calls to each other. Well, | |
| 328 | // nothing is perfect. | |
| 329 | ||
| 382 | 330 | |
| 331 | ||
| 332 | ||
| 333 | ||
| 325 | 334 | // Sudoku | 
| 335 | //======== | |
| 336 | ||
| 337 | // THE POINT OF THIS CODE IS NOT TO BE SUPER | |
| 338 | // EFFICIENT AND FAST, just explaining exhaustive | |
| 339 | // depth-first search | |
| 340 | ||
| 341 | ||
| 342 | val game0 = """.14.6.3.. | |
| 343 | |62...4..9 | |
| 344 | |.8..5.6.. | |
| 345 | |.6.2....3 | |
| 346 | |.7..1..5. | |
| 347 | |5....9.6. | |
| 348 | |..6.2..3. | |
| 349 | |1..5...92 | |
| 350 |               |..7.9.41.""".stripMargin.replaceAll("\\n", "")
 | |
| 351 | ||
| 383 | 352 | |
| 326 | 353 | |
| 325 | 354 | type Pos = (Int, Int) | 
| 355 | val EmptyValue = '.' | |
| 356 | val MaxValue = 9 | |
| 357 | ||
| 383 | 358 | def pretty(game: String): String = | 
| 359 |   "\n" + (game.grouped(MaxValue).mkString("\n"))
 | |
| 360 | ||
| 361 | pretty(game0) | |
| 362 | ||
| 363 | ||
| 325 | 364 | val allValues = "123456789".toList | 
| 365 | val indexes = (0 to 8).toList | |
| 366 | ||
| 367 | def empty(game: String) = game.indexOf(EmptyValue) | |
| 368 | def isDone(game: String) = empty(game) == -1 | |
| 383 | 369 | def emptyPosition(game: String) = {
 | 
| 370 | val e = empty(game) | |
| 371 | (e % MaxValue, e / MaxValue) | |
| 372 | } | |
| 325 | 373 | |
| 374 | def get_row(game: String, y: Int) = | |
| 375 | indexes.map(col => game(y * MaxValue + col)) | |
| 376 | def get_col(game: String, x: Int) = | |
| 377 | indexes.map(row => game(x + row * MaxValue)) | |
| 378 | ||
| 383 | 379 | //get_row(game0, 0) | 
| 380 | //get_row(game0, 1) | |
| 381 | //get_col(game0, 0) | |
| 326 | 382 | |
| 325 | 383 | def get_box(game: String, pos: Pos): List[Char] = {
 | 
| 384 | def base(p: Int): Int = (p / 3) * 3 | |
| 385 | val x0 = base(pos._1) | |
| 386 | val y0 = base(pos._2) | |
| 387 | val ys = (y0 until y0 + 3).toList | |
| 383 | 388 | (x0 until x0 + 3).toList | 
| 389 | .flatMap(x => ys.map(y => game(x + y * MaxValue))) | |
| 325 | 390 | } | 
| 391 | ||
| 383 | 392 | |
| 325 | 393 | //get_box(game0, (3, 1)) | 
| 394 | ||
| 395 | ||
| 396 | // this is not mutable!! | |
| 397 | def update(game: String, pos: Int, value: Char): String = | |
| 398 | game.updated(pos, value) | |
| 399 | ||
| 400 | def toAvoid(game: String, pos: Pos): List[Char] = | |
| 383 | 401 | (get_col(game, pos._1) ++ | 
| 402 | get_row(game, pos._2) ++ | |
| 403 | get_box(game, pos)) | |
| 325 | 404 | |
| 405 | def candidates(game: String, pos: Pos): List[Char] = | |
| 406 | allValues.diff(toAvoid(game, pos)) | |
| 407 | ||
| 408 | //candidates(game0, (0,0)) | |
| 409 | ||
| 410 | ||
| 411 | def search(game: String): List[String] = {
 | |
| 412 | if (isDone(game)) List(game) | |
| 413 |   else {
 | |
| 414 | val cs = candidates(game, emptyPosition(game)) | |
| 383 | 415 | cs.map(c => search(update(game, empty(game), c))).flatten | 
| 325 | 416 | } | 
| 417 | } | |
| 418 | ||
| 383 | 419 | pretty(game0) | 
| 325 | 420 | search(game0).map(pretty) | 
| 421 | ||
| 422 | val game1 = """23.915... | |
| 423 | |...2..54. | |
| 424 | |6.7...... | |
| 425 | |..1.....9 | |
| 426 | |89.5.3.17 | |
| 427 | |5.....6.. | |
| 428 | |......9.5 | |
| 429 | |.16..7... | |
| 430 |               |...329..1""".stripMargin.replaceAll("\\n", "")
 | |
| 431 | ||
| 432 | search(game1).map(pretty) | |
| 433 | ||
| 434 | // a game that is in the hard category | |
| 435 | val game2 = """8........ | |
| 436 | |..36..... | |
| 437 | |.7..9.2.. | |
| 438 | |.5...7... | |
| 439 | |....457.. | |
| 440 | |...1...3. | |
| 441 | |..1....68 | |
| 442 | |..85...1. | |
| 443 |               |.9....4..""".stripMargin.replaceAll("\\n", "")
 | |
| 444 | ||
| 445 | search(game2).map(pretty) | |
| 446 | ||
| 447 | // game with multiple solutions | |
| 448 | val game3 = """.8...9743 | |
| 449 | |.5...8.1. | |
| 450 | |.1....... | |
| 451 | |8....5... | |
| 452 | |...8.4... | |
| 453 | |...3....6 | |
| 454 | |.......7. | |
| 455 | |.3.5...8. | |
| 456 |               |9724...5.""".stripMargin.replaceAll("\\n", "")
 | |
| 457 | ||
| 458 | search(game3).map(pretty).foreach(println) | |
| 459 | ||
| 460 | // for measuring time | |
| 461 | def time_needed[T](i: Int, code: => T) = {
 | |
| 462 | val start = System.nanoTime() | |
| 463 | for (j <- 1 to i) code | |
| 464 | val end = System.nanoTime() | |
| 465 |   s"${(end - start) / 1.0e9} secs"
 | |
| 466 | } | |
| 467 | ||
| 468 | time_needed(1, search(game2)) | |
| 469 | ||
| 470 | ||
| 471 | ||
| 384 | 472 | // tail recursive version that searches | 
| 473 | // for all Sudoku solutions | |
| 325 | 474 | import scala.annotation.tailrec | 
| 475 | ||
| 476 | @tailrec | |
| 384 | 477 | def searchT(games: List[String], sols: List[String]): List[String] = | 
| 478 |  games match {
 | |
| 479 | case Nil => sols | |
| 480 |     case game::rest => {
 | |
| 481 | if (isDone(game)) searchT(rest, game::sols) | |
| 482 |       else {
 | |
| 483 | val cs = candidates(game, emptyPosition(game)) | |
| 484 | searchT(cs.map(c => update(game, empty(game), c)) ::: rest, sols) | |
| 485 | } | |
| 486 | } | |
| 487 | } | |
| 325 | 488 | |
| 489 | searchT(List(game3), List()).map(pretty) | |
| 490 | ||
| 491 | ||
| 492 | // tail recursive version that searches | |
| 493 | // for a single solution | |
| 494 | ||
| 495 | def search1T(games: List[String]): Option[String] = games match {
 | |
| 496 | case Nil => None | |
| 497 |   case game::rest => {
 | |
| 498 | if (isDone(game)) Some(game) | |
| 499 |     else {
 | |
| 500 | val cs = candidates(game, emptyPosition(game)) | |
| 501 | search1T(cs.map(c => update(game, empty(game), c)) ::: rest) | |
| 502 | } | |
| 503 | } | |
| 504 | } | |
| 505 | ||
| 506 | search1T(List(game3)).map(pretty) | |
| 507 | time_needed(1, search1T(List(game3))) | |
| 508 | time_needed(1, search1T(List(game2))) | |
| 509 | ||
| 510 | // game with multiple solutions | |
| 511 | val game3 = """.8...9743 | |
| 512 | |.5...8.1. | |
| 513 | |.1....... | |
| 514 | |8....5... | |
| 515 | |...8.4... | |
| 516 | |...3....6 | |
| 517 | |.......7. | |
| 518 | |.3.5...8. | |
| 519 |               |9724...5.""".stripMargin.replaceAll("\\n", "")
 | |
| 520 | ||
| 521 | searchT(List(game3), Nil).map(pretty) | |
| 522 | search1T(List(game3)).map(pretty) | |
| 523 | ||
| 524 | ||
| 525 | ||
| 222 | 526 | |
| 527 | ||
| 528 | ||
| 325 | 529 | // Cool Stuff in Scala | 
| 530 | //===================== | |
| 531 | ||
| 532 | ||
| 533 | // Implicits or How to Pimp your Library | |
| 534 | //====================================== | |
| 535 | // | |
| 536 | // For example adding your own methods to Strings: | |
| 537 | // Imagine you want to increment strings, like | |
| 538 | // | |
| 539 | // "HAL".increment | |
| 540 | // | |
| 541 | // you can avoid ugly fudges, like a MyString, by | |
| 542 | // using implicit conversions. | |
| 543 | ||
| 544 | ||
| 545 | implicit class MyString(s: String) {
 | |
| 546 | def increment = s.map(c => (c + 1).toChar) | |
| 547 | } | |
| 548 | ||
| 415 | 549 | "HAL".increment.map(_.toInt) | 
| 325 | 550 | |
| 551 | ||
| 552 | // Abstract idea: | |
| 553 | // In that version implicit conversions were used to solve the | |
| 554 | // late extension problem; namely, given a class C and a class T, | |
| 555 | // how to have C extend T without touching or recompiling C. | |
| 556 | // Conversions add a wrapper when a member of T is requested | |
| 557 | // from an instance of C. | |
| 558 | ||
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 559 | |
| 325 | 560 | |
| 561 | import scala.concurrent.duration.{TimeUnit,SECONDS,MINUTES}
 | |
| 562 | ||
| 563 | case class Duration(time: Long, unit: TimeUnit) {
 | |
| 564 | def +(o: Duration) = | |
| 565 | Duration(time + unit.convert(o.time, o.unit), unit) | |
| 566 | } | |
| 567 | ||
| 568 | implicit class Int2Duration(that: Int) {
 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 569 | def seconds = Duration(that, SECONDS) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 570 | def minutes = Duration(that, MINUTES) | 
| 325 | 571 | } | 
| 572 | ||
| 573 | 5.seconds + 2.minutes //Duration(125L, SECONDS ) | |
| 574 | 2.minutes + 60.seconds | |
| 575 | ||
| 576 | ||
| 577 | ||
| 578 | ||
| 579 | // Regular expressions - the power of DSLs in Scala | |
| 580 | //================================================== | |
| 581 | ||
| 582 | abstract class Rexp | |
| 583 | case object ZERO extends Rexp // nothing | |
| 584 | case object ONE extends Rexp // the empty string | |
| 585 | case class CHAR(c: Char) extends Rexp // a character c | |
| 586 | case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative r1 + r2 | |
| 587 | case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence r1 . r2 | |
| 588 | case class STAR(r: Rexp) extends Rexp // star r* | |
| 589 | ||
| 590 | ||
| 591 | ||
| 592 | // writing (ab)* in the format above is | |
| 593 | // tedious | |
| 594 | val r0 = STAR(SEQ(CHAR('a'), CHAR('b')))
 | |
| 595 | ||
| 596 | ||
| 597 | // some convenience for typing in regular expressions | |
| 598 | import scala.language.implicitConversions | |
| 599 | import scala.language.reflectiveCalls | |
| 600 | ||
| 601 | def charlist2rexp(s: List[Char]): Rexp = s match {
 | |
| 602 | case Nil => ONE | |
| 603 | case c::Nil => CHAR(c) | |
| 604 | case c::s => SEQ(CHAR(c), charlist2rexp(s)) | |
| 605 | } | |
| 326 | 606 | |
| 325 | 607 | implicit def string2rexp(s: String): Rexp = | 
| 608 | charlist2rexp(s.toList) | |
| 609 | ||
| 415 | 610 | val r1 = STAR("ab")
 | 
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 611 | val r2 = STAR("hello") | STAR("world")
 | 
| 325 | 612 | |
| 613 | ||
| 614 | implicit def RexpOps (r: Rexp) = new {
 | |
| 615 | def | (s: Rexp) = ALT(r, s) | |
| 616 | def % = STAR(r) | |
| 617 | def ~ (s: Rexp) = SEQ(r, s) | |
| 618 | } | |
| 619 | ||
| 620 | implicit def stringOps (s: String) = new {
 | |
| 621 | def | (r: Rexp) = ALT(s, r) | |
| 622 | def | (r: String) = ALT(s, r) | |
| 623 | def % = STAR(s) | |
| 624 | def ~ (r: Rexp) = SEQ(s, r) | |
| 625 | def ~ (r: String) = SEQ(s, r) | |
| 626 | } | |
| 627 | ||
| 628 | //example regular expressions | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 629 | |
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 630 | |
| 326 | 631 | val digit = ("0" | "1" | "2" | "3" | "4" | 
 | 
| 632 | "5" | "6" | "7" | "8" | "9") | |
| 325 | 633 | val sign = "+" | "-" | "" | 
| 634 | val number = sign ~ digit ~ digit.% | |
| 635 | ||
| 636 | ||
| 637 | ||
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 638 | |
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 639 | // In mandelbrot.scala I used complex (imaginary) numbers | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 640 | // and implemented the usual arithmetic operations for complex | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 641 | // numbers. | 
| 325 | 642 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 643 | case class Complex(re: Double, im: Double) { 
 | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 644 | // represents the complex number re + im * i | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 645 | def +(that: Complex) = Complex(this.re + that.re, this.im + that.im) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 646 | def -(that: Complex) = Complex(this.re - that.re, this.im - that.im) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 647 | def *(that: Complex) = Complex(this.re * that.re - this.im * that.im, | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 648 | this.re * that.im + that.re * this.im) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 649 | def *(that: Double) = Complex(this.re * that, this.im * that) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 650 | def abs = Math.sqrt(this.re * this.re + this.im * this.im) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 651 | } | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 652 | |
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 653 | val test = Complex(1, 2) + Complex (3, 4) | 
| 222 | 654 | |
| 325 | 655 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 656 | // ...to allow the notation n + m * i | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 657 | import scala.language.implicitConversions | 
| 325 | 658 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 659 | val i = Complex(0, 1) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 660 | implicit def double2complex(re: Double) = Complex(re, 0) | 
| 222 | 661 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 662 | val inum1 = -2.0 + -1.5 * i | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 663 | val inum2 = 1.0 + 1.5 * i |