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