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