| author | Christian Urban <christian.urban@kcl.ac.uk> | 
| Mon, 25 Dec 2023 01:10:55 +0100 | |
| changeset 479 | 78cb5cdda3c3 | 
| parent 478 | 0e6ca70496c1 | 
| child 491 | 2a30c7dfe3ed | 
| permissions | -rw-r--r-- | 
| 222 | 1 | // Scala Lecture 4 | 
| 2 | //================= | |
| 3 | ||
| 478 | 4 | // pattern-matching | 
| 415 | 5 | // tail-recursion | 
| 6 | // polymorphic types | |
| 478 | 7 | |
| 8 | ||
| 9 | ||
| 10 | // Pattern Matching | |
| 11 | //================== | |
| 12 | ||
| 13 | // A powerful tool which has even landed in Java during | |
| 14 | // the last few years (https://inside.java/2021/06/13/podcast-017/). | |
| 15 | // ...Scala already has it for many years and the concept is | |
| 16 | // older than your friendly lecturer, that is stone old ;o) | |
| 415 | 17 | |
| 478 | 18 | // The general schema: | 
| 19 | // | |
| 20 | //    expression match {
 | |
| 21 | // case pattern1 => expression1 | |
| 22 | // case pattern2 => expression2 | |
| 23 | // ... | |
| 24 | // case patternN => expressionN | |
| 25 | // } | |
| 26 | ||
| 27 | ||
| 28 | // recall | |
| 29 | def len(xs: List[Int]) : Int = {
 | |
| 30 | if (xs == Nil) 0 | |
| 31 | else 1 + len(xs.tail) | |
| 32 | } | |
| 415 | 33 | |
| 478 | 34 | def len(xs: List[Int]) : Int = xs match {
 | 
| 35 | case Nil => 0 | |
| 36 | case _::xs => 1 + len(xs) | |
| 37 | } | |
| 38 | ||
| 39 | len(Nil) | |
| 40 | len(List(1,2,3,4)) | |
| 41 | ||
| 42 | ||
| 43 | List(1,2,3,4).map(x => x * x) | |
| 44 | ||
| 45 | def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = | |
| 46 |   lst match {
 | |
| 47 | case Nil => Nil | |
| 48 | case foo::xs => f(foo) :: my_map_int(xs, f) | |
| 49 | } | |
| 50 | ||
| 51 | def my_map_option(opt: Option[Int], f: Int => Int) : Option[Int] = | |
| 52 |   opt match {
 | |
| 53 | case None => None | |
| 54 |     case Some(x) => {
 | |
| 55 | Some(f(x)) | |
| 56 | } | |
| 57 | } | |
| 58 | ||
| 59 | my_map_option(None, x => x * x) | |
| 60 | my_map_option(Some(8), x => x * x) | |
| 415 | 61 | |
| 62 | ||
| 478 | 63 | // you can also have cases combined | 
| 64 | def season(month: String) : String = month match {
 | |
| 65 | case "March" | "April" | "May" => "It's spring" | |
| 66 | case "June" | "July" | "August" => "It's summer" | |
| 67 | case "September" | "October" | "November" => "It's autumn" | |
| 68 | case "December" => "It's winter" | |
| 69 | case "January" | "February" => "It's unfortunately winter" | |
| 70 | case _ => "Wrong month" | |
| 71 | } | |
| 72 | ||
| 73 | // pattern-match on integers | |
| 74 | ||
| 75 | def fib(n: Int) : Int = n match { 
 | |
| 76 | case 0 | 1 => 1 | |
| 77 | case _ => fib(n - 1) + fib(n - 2) | |
| 78 | } | |
| 79 | ||
| 80 | fib(10) | |
| 81 | ||
| 82 | // pattern-match on results | |
| 83 | ||
| 84 | // Silly: fizz buzz | |
| 85 | def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
 | |
| 86 | case (0, 0) => "fizz buzz" | |
| 87 | case (0, _) => "fizz" | |
| 88 | case (_, 0) => "buzz" | |
| 89 | case _ => n.toString | |
| 90 | } | |
| 91 | ||
| 92 | for (n <- 1 to 20) | |
| 93 | println(fizz_buzz(n)) | |
| 94 | ||
| 95 | // guards in pattern-matching | |
| 96 | ||
| 97 | def foo(xs: List[Int]) : String = xs match {
 | |
| 98 | case Nil => s"this list is empty" | |
| 99 | case x :: xs if x % 2 == 0 | |
| 100 | => s"the first elemnt is even" | |
| 101 | case x if len(x) == | |
| 102 | => s"this list has exactly two elements" | |
| 103 | case x :: y :: rest if x == y | |
| 104 | => s"this has two elemnts that are the same" | |
| 105 | case hd :: tl => s"this list is standard $hd::$tl" | |
| 106 | } | |
| 107 | ||
| 108 | foo(Nil) | |
| 109 | foo(List(1,2,3)) | |
| 110 | foo(List(1,1)) | |
| 111 | foo(List(1,1,2,3)) | |
| 112 | foo(List(2,2,2,3)) | |
| 113 | ||
| 114 | ||
| 115 | ||
| 116 | ||
| 117 | abstract class Colour | |
| 118 | case object Red extends Colour | |
| 119 | case object Green extends Colour | |
| 120 | case object Blue extends Colour | |
| 121 | case object Yellow extends Colour | |
| 122 | ||
| 123 | ||
| 124 | def fav_colour(c: Colour) : Boolean = c match {
 | |
| 125 | case Green => true | |
| 126 | case Red => true | |
| 127 | case _ => false | |
| 128 | } | |
| 129 | ||
| 130 | fav_colour(Blue) | |
| 415 | 131 | |
| 132 | ||
| 478 | 133 | // ... a tiny bit more useful: Roman Numerals | 
| 134 | ||
| 135 | sealed abstract class RomanDigit | |
| 136 | case object I extends RomanDigit | |
| 137 | case object V extends RomanDigit | |
| 138 | case object X extends RomanDigit | |
| 139 | case object L extends RomanDigit | |
| 140 | case object C extends RomanDigit | |
| 141 | case object D extends RomanDigit | |
| 142 | case object M extends RomanDigit | |
| 143 | ||
| 144 | type RomanNumeral = List[RomanDigit] | |
| 145 | ||
| 146 | List(I, M,C,D,X,X,V,I,I, A) | |
| 147 | ||
| 148 | /* | |
| 149 | I -> 1 | |
| 150 | II -> 2 | |
| 151 | III -> 3 | |
| 152 | IV -> 4 | |
| 153 | V -> 5 | |
| 154 | VI -> 6 | |
| 155 | VII -> 7 | |
| 156 | VIII -> 8 | |
| 157 | IX -> 9 | |
| 158 | X -> 10 | |
| 159 | */ | |
| 415 | 160 | |
| 478 | 161 | def RomanNumeral2Int(rs: RomanNumeral): Int = rs match { 
 | 
| 162 | case Nil => 0 | |
| 163 | case M::r => 1000 + RomanNumeral2Int(r) | |
| 164 | case C::M::r => 900 + RomanNumeral2Int(r) | |
| 165 | case D::r => 500 + RomanNumeral2Int(r) | |
| 166 | case C::D::r => 400 + RomanNumeral2Int(r) | |
| 167 | case C::r => 100 + RomanNumeral2Int(r) | |
| 168 | case X::C::r => 90 + RomanNumeral2Int(r) | |
| 169 | case L::r => 50 + RomanNumeral2Int(r) | |
| 170 | case X::L::r => 40 + RomanNumeral2Int(r) | |
| 171 | case X::r => 10 + RomanNumeral2Int(r) | |
| 172 | case I::X::r => 9 + RomanNumeral2Int(r) | |
| 173 | case V::r => 5 + RomanNumeral2Int(r) | |
| 174 | case I::V::r => 4 + RomanNumeral2Int(r) | |
| 175 | case I::r => 1 + RomanNumeral2Int(r) | |
| 176 | } | |
| 177 | ||
| 178 | RomanNumeral2Int(List(I,V)) // 4 | |
| 179 | RomanNumeral2Int(List(I,I,I,I)) // 4 (invalid Roman number) | |
| 180 | RomanNumeral2Int(List(V,I)) // 6 | |
| 181 | RomanNumeral2Int(List(I,X)) // 9 | |
| 182 | RomanNumeral2Int(List(M,C,M,L,X,X,I,X)) // 1979 | |
| 183 | RomanNumeral2Int(List(M,M,X,V,I,I)) // 2017 | |
| 184 | ||
| 185 | abstract class Tree | |
| 186 | case class Leaf(x: Int) | |
| 187 | case class Branch(tl: Tree, tr: Tree) | |
| 415 | 188 | |
| 189 | ||
| 478 | 190 | abstract class Rexp | 
| 191 | case object ZERO extends Rexp // matches nothing | |
| 192 | case object ONE extends Rexp // matches the empty string | |
| 193 | case class CHAR(c: Char) extends Rexp // matches a character c | |
| 194 | case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative | |
| 195 | case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence | |
| 196 | case class STAR(r: Rexp) extends Rexp // star | |
| 415 | 197 | |
| 478 | 198 | def depth(r: Rexp) : Int = r match {
 | 
| 199 | case ZERO => 1 | |
| 200 | case ONE => 1 | |
| 201 | case CHAR(_) => 1 | |
| 202 | case ALT(r1, r2) => 1 + List(depth(r1), depth(r2)).max | |
| 203 | case SEQ(r1, r2) => 1 + List(depth(r1), depth(r2)).max | |
| 204 | case STAR(r1) => 1 + depth(r1) | |
| 205 | } | |
| 206 | ||
| 207 | ||
| 208 | // Trees (example of an Algebraic Datatype) | |
| 209 | ||
| 210 | ||
| 211 | abstract class Tree | |
| 212 | case class Leaf(x: Int) extends Tree | |
| 213 | case class Node(s: String, left: Tree, right: Tree) extends Tree | |
| 214 | ||
| 215 | val lf = Leaf(20) | |
| 216 | val tr = Node("foo", Leaf(10), Leaf(23))
 | |
| 217 | ||
| 218 | val lst : List[Tree] = List(lf, tr) | |
| 219 | ||
| 415 | 220 | |
| 222 | 221 | |
| 325 | 222 | // expressions (essentially trees) | 
| 223 | ||
| 478 | 224 | sealed abstract class Exp | 
| 325 | 225 | case class N(n: Int) extends Exp // for numbers | 
| 226 | case class Plus(e1: Exp, e2: Exp) extends Exp | |
| 227 | case class Times(e1: Exp, e2: Exp) extends Exp | |
| 228 | ||
| 229 | def string(e: Exp) : String = e match {
 | |
| 230 | case N(n) => s"$n" | |
| 231 |   case Plus(e1, e2) => s"(${string(e1)} + ${string(e2)})" 
 | |
| 232 |   case Times(e1, e2) => s"(${string(e1)} * ${string(e2)})"
 | |
| 233 | } | |
| 234 | ||
| 235 | val e = Plus(N(9), Times(N(3), N(4))) | |
| 478 | 236 | println(e.toString) | 
| 325 | 237 | println(string(e)) | 
| 238 | ||
| 239 | def eval(e: Exp) : Int = e match {
 | |
| 240 | case N(n) => n | |
| 241 | case Plus(e1, e2) => eval(e1) + eval(e2) | |
| 242 | case Times(e1, e2) => eval(e1) * eval(e2) | |
| 243 | } | |
| 244 | ||
| 245 | println(eval(e)) | |
| 246 | ||
| 247 | // simplification rules: | |
| 248 | // e + 0, 0 + e => e | |
| 249 | // e * 0, 0 * e => 0 | |
| 250 | // e * 1, 1 * e => e | |
| 326 | 251 | // | 
| 478 | 252 | // (....9 ....) | 
| 325 | 253 | |
| 254 | def simp(e: Exp) : Exp = e match {
 | |
| 255 | case N(n) => N(n) | |
| 256 |   case Plus(e1, e2) => (simp(e1), simp(e2)) match {
 | |
| 257 | case (N(0), e2s) => e2s | |
| 258 | case (e1s, N(0)) => e1s | |
| 259 | case (e1s, e2s) => Plus(e1s, e2s) | |
| 260 | } | |
| 261 |   case Times(e1, e2) => (simp(e1), simp(e2)) match {
 | |
| 262 | case (N(0), _) => N(0) | |
| 263 | case (_, N(0)) => N(0) | |
| 264 | case (N(1), e2s) => e2s | |
| 265 | case (e1s, N(1)) => e1s | |
| 266 | case (e1s, e2s) => Times(e1s, e2s) | |
| 267 | } | |
| 268 | } | |
| 269 | ||
| 270 | ||
| 271 | val e2 = Times(Plus(N(0), N(1)), Plus(N(0), N(9))) | |
| 272 | println(string(e2)) | |
| 273 | println(string(simp(e2))) | |
| 274 | ||
| 275 | ||
| 478 | 276 | |
| 277 | ||
| 278 | ||
| 279 | ||
| 280 | ||
| 325 | 281 | // Tokens and Reverse Polish Notation | 
| 282 | abstract class Token | |
| 283 | case class T(n: Int) extends Token | |
| 284 | case object PL extends Token | |
| 285 | case object TI extends Token | |
| 286 | ||
| 287 | // transfroming an Exp into a list of tokens | |
| 288 | def rp(e: Exp) : List[Token] = e match {
 | |
| 289 | case N(n) => List(T(n)) | |
| 290 | case Plus(e1, e2) => rp(e1) ::: rp(e2) ::: List(PL) | |
| 291 | case Times(e1, e2) => rp(e1) ::: rp(e2) ::: List(TI) | |
| 292 | } | |
| 293 | println(string(e2)) | |
| 294 | println(rp(e2)) | |
| 295 | ||
| 326 | 296 | def comp(ls: List[Token], st: List[Int] = Nil) : Int = (ls, st) match {
 | 
| 325 | 297 | case (Nil, st) => st.head | 
| 298 | case (T(n)::rest, st) => comp(rest, n::st) | |
| 299 | case (PL::rest, n1::n2::st) => comp(rest, n1 + n2::st) | |
| 300 | case (TI::rest, n1::n2::st) => comp(rest, n1 * n2::st) | |
| 301 | } | |
| 302 | ||
| 326 | 303 | comp(rp(e)) | 
| 325 | 304 | |
| 305 | def proc(s: String) : Token = s match {
 | |
| 306 | case "+" => PL | |
| 307 | case "*" => TI | |
| 308 | case _ => T(s.toInt) | |
| 309 | } | |
| 310 | ||
| 311 | comp("1 2 + 4 * 5 + 3 +".split(" ").toList.map(proc), Nil)
 | |
| 312 | ||
| 313 | ||
| 478 | 314 | // Tail recursion | 
| 315 | //================ | |
| 316 | ||
| 317 | def fact(n: BigInt): BigInt = | |
| 318 | if (n == 0) 1 else n * fact(n - 1) | |
| 319 | ||
| 320 | ||
| 321 | fact(10) | |
| 322 | fact(1000) | |
| 323 | fact(100000) | |
| 324 | ||
| 325 | ||
| 326 | def factT(n: BigInt, acc: BigInt): BigInt = | |
| 327 | if (n == 0) acc else factT(n - 1, n * acc) | |
| 328 | ||
| 329 | ||
| 330 | factT(10, 1) | |
| 331 | println(factT(100000, 1)) | |
| 332 | ||
| 333 | ||
| 334 | // there is a flag for ensuring a function is tail recursive | |
| 335 | import scala.annotation.tailrec | |
| 336 | ||
| 337 | @tailrec | |
| 338 | def factT(n: BigInt, acc: BigInt): BigInt = | |
| 339 | if (n == 0) acc else factT(n - 1, n * acc) | |
| 340 | ||
| 341 | factT(100000, 1) | |
| 342 | ||
| 343 | // for tail-recursive functions the Scala compiler | |
| 344 | // generates loop-like code, which does not need | |
| 345 | // to allocate stack-space in each recursive | |
| 346 | // call; Scala can do this only for tail-recursive | |
| 347 | // functions | |
| 348 | ||
| 349 | // Moral: Whenever a recursive function is resource-critical | |
| 350 | // (i.e. works with a large recursion depth), then you need to | |
| 351 | // write it in tail-recursive fashion. | |
| 352 | // | |
| 353 | // Unfortuantely, Scala because of current limitations in | |
| 354 | // the JVM is not as clever as other functional languages. It can | |
| 355 | // only optimise "self-tail calls". This excludes the cases of | |
| 356 | // multiple functions making tail calls to each other. Well, | |
| 357 | // nothing is perfect. | |
| 358 | ||
| 359 | ||
| 360 | ||
| 380 | 361 | // Polymorphic Types | 
| 362 | //=================== | |
| 363 | ||
| 364 | // You do not want to write functions like contains, first, | |
| 365 | // length and so on for every type of lists. | |
| 366 | ||
| 367 | def length_int_list(lst: List[Int]): Int = lst match {
 | |
| 368 | case Nil => 0 | |
| 452 | 369 | case _::xs => 1 + length_int_list(xs) | 
| 380 | 370 | } | 
| 371 | ||
| 372 | length_int_list(List(1, 2, 3, 4)) | |
| 373 | ||
| 374 | def length_string_list(lst: List[String]): Int = lst match {
 | |
| 375 | case Nil => 0 | |
| 376 | case _::xs => 1 + length_string_list(xs) | |
| 377 | } | |
| 378 | ||
| 379 | length_string_list(List("1", "2", "3", "4"))
 | |
| 380 | ||
| 381 | ||
| 382 | // you can make the function parametric in type(s) | |
| 383 | ||
| 384 | def length[A](lst: List[A]): Int = lst match {
 | |
| 385 | case Nil => 0 | |
| 386 | case x::xs => 1 + length(xs) | |
| 387 | } | |
| 388 | length(List("1", "2", "3", "4"))
 | |
| 389 | length(List(1, 2, 3, 4)) | |
| 390 | ||
| 452 | 391 | |
| 392 | length[String](List(1, 2, 3, 4)) | |
| 380 | 393 | |
| 394 | ||
| 395 | def map[A, B](lst: List[A], f: A => B): List[B] = lst match {
 | |
| 396 | case Nil => Nil | |
| 397 | case x::xs => f(x)::map(xs, f) | |
| 398 | } | |
| 399 | ||
| 400 | map(List(1, 2, 3, 4), (x: Int) => x.toString) | |
| 401 | ||
| 402 | ||
| 403 | // should be | |
| 404 | def first[A, B](xs: List[A], f: A => Option[B]) : Option[B] = ??? | |
| 405 | ||
| 406 | // Type inference is local in Scala | |
| 407 | ||
| 408 | def id[T](x: T) : T = x | |
| 409 | ||
| 410 | val x = id(322) // Int | |
| 411 | val y = id("hey")        // String
 | |
| 412 | val z = id(Set(1,2,3,4)) // Set[Int] | |
| 413 | ||
| 414 | ||
| 415 | // The type variable concept in Scala can get really complicated. | |
| 416 | // | |
| 417 | // - variance (OO) | |
| 418 | // - bounds (subtyping) | |
| 419 | // - quantification | |
| 420 | ||
| 421 | // Java has issues with this too: Java allows | |
| 422 | // to write the following incorrect code, and | |
| 423 | // only recovers by raising an exception | |
| 424 | // at runtime. | |
| 425 | ||
| 426 | // Object[] arr = new Integer[10]; | |
| 427 | // arr[0] = "Hello World"; | |
| 428 | ||
| 429 | ||
| 430 | // Scala gives you a compile-time error, which | |
| 431 | // is much better. | |
| 432 | ||
| 433 | var arr = Array[Int]() | |
| 434 | arr(0) = "Hello World" | |
| 435 | ||
| 436 | ||
| 437 | ||
| 438 | ||
| 439 | // Function definitions again | |
| 440 | //============================ | |
| 441 | ||
| 442 | // variable arguments | |
| 443 | ||
| 444 | def printAll(strings: String*) = {
 | |
| 445 | strings.foreach(println) | |
| 446 | } | |
| 447 | ||
| 448 | printAll() | |
| 449 | printAll("foo")
 | |
| 450 | printAll("foo", "bar")
 | |
| 451 | printAll("foo", "bar", "baz")
 | |
| 452 | ||
| 453 | // pass a list to the varargs field | |
| 454 | val fruits = List("apple", "banana", "cherry")
 | |
| 455 | ||
| 456 | printAll(fruits: _*) | |
| 457 | ||
| 458 | ||
| 459 | // you can also implement your own string interpolations | |
| 460 | import scala.language.implicitConversions | |
| 461 | import scala.language.reflectiveCalls | |
| 462 | ||
| 463 | implicit def sring_inters(sc: StringContext) = new {
 | |
| 464 |     def i(args: Any*): String = s"${sc.s(args:_*)}\n"
 | |
| 465 | } | |
| 466 | ||
| 467 | i"add ${3+2} ${3 * 3}" 
 | |
| 468 | ||
| 469 | ||
| 470 | // default arguments | |
| 471 | ||
| 472 | def length[A](xs: List[A]) : Int = xs match {
 | |
| 473 | case Nil => 0 | |
| 474 | case _ :: tail => 1 + length(tail) | |
| 475 | } | |
| 476 | ||
| 477 | def lengthT[A](xs: List[A], acc : Int = 0) : Int = xs match {
 | |
| 478 | case Nil => acc | |
| 479 | case _ :: tail => lengthT(tail, 1 + acc) | |
| 480 | } | |
| 481 | ||
| 482 | lengthT(List.fill(100000)(1)) | |
| 483 | ||
| 484 | ||
| 485 | def fact(n: BigInt, acc: BigInt = 1): BigInt = | |
| 486 | if (n == 0) acc else fact(n - 1, n * acc) | |
| 487 | ||
| 488 | fact(10) | |
| 489 | ||
| 490 | ||
| 491 | ||
| 492 | // currying (Haskell Curry) | |
| 493 | ||
| 494 | def add(x: Int, y: Int) = x + y | |
| 495 | ||
| 496 | List(1,2,3,4,5).map(x => add(3, x)) | |
| 497 | ||
| 498 | def add2(x: Int)(y: Int) = x + y | |
| 499 | ||
| 500 | List(1,2,3,4,5).map(add2(3)) | |
| 501 | ||
| 502 | val a3 : Int => Int = add2(3) | |
| 503 | ||
| 504 | // currying helps sometimes with type inference | |
| 505 | ||
| 506 | def find[A](xs: List[A])(pred: A => Boolean): Option[A] = {
 | |
| 507 |   xs match {
 | |
| 508 | case Nil => None | |
| 509 | case hd :: tl => | |
| 510 | if (pred(hd)) Some(hd) else find(tl)(pred) | |
| 511 | } | |
| 512 | } | |
| 513 | ||
| 514 | find(List(1, 2, 3))(x => x % 2 == 0) | |
| 515 | ||
| 516 | // Source.fromURL(url)(encoding) | |
| 517 | // Source.fromFile(name)(encoding) | |
| 325 | 518 | |
| 519 | ||
| 384 | 520 | |
| 382 | 521 | |
| 522 | ||
| 523 | ||
| 524 | ||
| 325 | 525 | // Sudoku | 
| 526 | //======== | |
| 527 | ||
| 528 | // THE POINT OF THIS CODE IS NOT TO BE SUPER | |
| 529 | // EFFICIENT AND FAST, just explaining exhaustive | |
| 530 | // depth-first search | |
| 531 | ||
| 532 | ||
| 533 | val game0 = """.14.6.3.. | |
| 534 | |62...4..9 | |
| 535 | |.8..5.6.. | |
| 536 | |.6.2....3 | |
| 537 | |.7..1..5. | |
| 538 | |5....9.6. | |
| 539 | |..6.2..3. | |
| 540 | |1..5...92 | |
| 541 |               |..7.9.41.""".stripMargin.replaceAll("\\n", "")
 | |
| 542 | ||
| 383 | 543 | |
| 326 | 544 | |
| 325 | 545 | type Pos = (Int, Int) | 
| 546 | val EmptyValue = '.' | |
| 547 | val MaxValue = 9 | |
| 548 | ||
| 383 | 549 | def pretty(game: String): String = | 
| 550 |   "\n" + (game.grouped(MaxValue).mkString("\n"))
 | |
| 551 | ||
| 552 | pretty(game0) | |
| 553 | ||
| 554 | ||
| 325 | 555 | val allValues = "123456789".toList | 
| 556 | val indexes = (0 to 8).toList | |
| 557 | ||
| 558 | def empty(game: String) = game.indexOf(EmptyValue) | |
| 559 | def isDone(game: String) = empty(game) == -1 | |
| 383 | 560 | def emptyPosition(game: String) = {
 | 
| 561 | val e = empty(game) | |
| 562 | (e % MaxValue, e / MaxValue) | |
| 563 | } | |
| 325 | 564 | |
| 565 | def get_row(game: String, y: Int) = | |
| 566 | indexes.map(col => game(y * MaxValue + col)) | |
| 567 | def get_col(game: String, x: Int) = | |
| 568 | indexes.map(row => game(x + row * MaxValue)) | |
| 569 | ||
| 383 | 570 | //get_row(game0, 0) | 
| 571 | //get_row(game0, 1) | |
| 572 | //get_col(game0, 0) | |
| 326 | 573 | |
| 325 | 574 | def get_box(game: String, pos: Pos): List[Char] = {
 | 
| 575 | def base(p: Int): Int = (p / 3) * 3 | |
| 576 | val x0 = base(pos._1) | |
| 577 | val y0 = base(pos._2) | |
| 578 | val ys = (y0 until y0 + 3).toList | |
| 383 | 579 | (x0 until x0 + 3).toList | 
| 580 | .flatMap(x => ys.map(y => game(x + y * MaxValue))) | |
| 325 | 581 | } | 
| 582 | ||
| 383 | 583 | |
| 325 | 584 | //get_box(game0, (3, 1)) | 
| 585 | ||
| 586 | ||
| 587 | // this is not mutable!! | |
| 588 | def update(game: String, pos: Int, value: Char): String = | |
| 589 | game.updated(pos, value) | |
| 590 | ||
| 591 | def toAvoid(game: String, pos: Pos): List[Char] = | |
| 383 | 592 | (get_col(game, pos._1) ++ | 
| 593 | get_row(game, pos._2) ++ | |
| 594 | get_box(game, pos)) | |
| 325 | 595 | |
| 596 | def candidates(game: String, pos: Pos): List[Char] = | |
| 597 | allValues.diff(toAvoid(game, pos)) | |
| 598 | ||
| 599 | //candidates(game0, (0,0)) | |
| 600 | ||
| 601 | ||
| 602 | def search(game: String): List[String] = {
 | |
| 603 | if (isDone(game)) List(game) | |
| 604 |   else {
 | |
| 605 | val cs = candidates(game, emptyPosition(game)) | |
| 383 | 606 | cs.map(c => search(update(game, empty(game), c))).flatten | 
| 325 | 607 | } | 
| 608 | } | |
| 609 | ||
| 383 | 610 | pretty(game0) | 
| 325 | 611 | search(game0).map(pretty) | 
| 612 | ||
| 613 | val game1 = """23.915... | |
| 614 | |...2..54. | |
| 615 | |6.7...... | |
| 616 | |..1.....9 | |
| 617 | |89.5.3.17 | |
| 618 | |5.....6.. | |
| 619 | |......9.5 | |
| 620 | |.16..7... | |
| 621 |               |...329..1""".stripMargin.replaceAll("\\n", "")
 | |
| 622 | ||
| 623 | search(game1).map(pretty) | |
| 624 | ||
| 625 | // a game that is in the hard category | |
| 626 | val game2 = """8........ | |
| 627 | |..36..... | |
| 628 | |.7..9.2.. | |
| 629 | |.5...7... | |
| 630 | |....457.. | |
| 631 | |...1...3. | |
| 632 | |..1....68 | |
| 633 | |..85...1. | |
| 634 |               |.9....4..""".stripMargin.replaceAll("\\n", "")
 | |
| 635 | ||
| 636 | search(game2).map(pretty) | |
| 637 | ||
| 638 | // game with multiple solutions | |
| 639 | val game3 = """.8...9743 | |
| 640 | |.5...8.1. | |
| 641 | |.1....... | |
| 642 | |8....5... | |
| 643 | |...8.4... | |
| 644 | |...3....6 | |
| 645 | |.......7. | |
| 646 | |.3.5...8. | |
| 647 |               |9724...5.""".stripMargin.replaceAll("\\n", "")
 | |
| 648 | ||
| 649 | search(game3).map(pretty).foreach(println) | |
| 650 | ||
| 651 | // for measuring time | |
| 652 | def time_needed[T](i: Int, code: => T) = {
 | |
| 653 | val start = System.nanoTime() | |
| 654 | for (j <- 1 to i) code | |
| 655 | val end = System.nanoTime() | |
| 656 |   s"${(end - start) / 1.0e9} secs"
 | |
| 657 | } | |
| 658 | ||
| 659 | time_needed(1, search(game2)) | |
| 660 | ||
| 661 | ||
| 662 | ||
| 384 | 663 | // tail recursive version that searches | 
| 664 | // for all Sudoku solutions | |
| 325 | 665 | import scala.annotation.tailrec | 
| 666 | ||
| 667 | @tailrec | |
| 384 | 668 | def searchT(games: List[String], sols: List[String]): List[String] = | 
| 669 |  games match {
 | |
| 670 | case Nil => sols | |
| 671 |     case game::rest => {
 | |
| 672 | if (isDone(game)) searchT(rest, game::sols) | |
| 673 |       else {
 | |
| 674 | val cs = candidates(game, emptyPosition(game)) | |
| 675 | searchT(cs.map(c => update(game, empty(game), c)) ::: rest, sols) | |
| 676 | } | |
| 677 | } | |
| 678 | } | |
| 325 | 679 | |
| 680 | searchT(List(game3), List()).map(pretty) | |
| 681 | ||
| 682 | ||
| 683 | // tail recursive version that searches | |
| 684 | // for a single solution | |
| 685 | ||
| 686 | def search1T(games: List[String]): Option[String] = games match {
 | |
| 687 | case Nil => None | |
| 688 |   case game::rest => {
 | |
| 689 | if (isDone(game)) Some(game) | |
| 690 |     else {
 | |
| 691 | val cs = candidates(game, emptyPosition(game)) | |
| 692 | search1T(cs.map(c => update(game, empty(game), c)) ::: rest) | |
| 693 | } | |
| 694 | } | |
| 695 | } | |
| 696 | ||
| 697 | search1T(List(game3)).map(pretty) | |
| 698 | time_needed(1, search1T(List(game3))) | |
| 699 | time_needed(1, search1T(List(game2))) | |
| 700 | ||
| 701 | // game with multiple solutions | |
| 702 | val game3 = """.8...9743 | |
| 703 | |.5...8.1. | |
| 704 | |.1....... | |
| 705 | |8....5... | |
| 706 | |...8.4... | |
| 707 | |...3....6 | |
| 708 | |.......7. | |
| 709 | |.3.5...8. | |
| 710 |               |9724...5.""".stripMargin.replaceAll("\\n", "")
 | |
| 711 | ||
| 712 | searchT(List(game3), Nil).map(pretty) | |
| 713 | search1T(List(game3)).map(pretty) | |
| 714 | ||
| 715 | ||
| 716 | ||
| 222 | 717 | |
| 718 | ||
| 719 | ||
| 325 | 720 | // Cool Stuff in Scala | 
| 721 | //===================== | |
| 722 | ||
| 723 | ||
| 724 | // Implicits or How to Pimp your Library | |
| 725 | //====================================== | |
| 726 | // | |
| 727 | // For example adding your own methods to Strings: | |
| 728 | // Imagine you want to increment strings, like | |
| 729 | // | |
| 730 | // "HAL".increment | |
| 731 | // | |
| 732 | // you can avoid ugly fudges, like a MyString, by | |
| 733 | // using implicit conversions. | |
| 734 | ||
| 452 | 735 | print("\n")
 | 
| 736 | print("""\n""")
 | |
| 325 | 737 | |
| 738 | implicit class MyString(s: String) {
 | |
| 739 | def increment = s.map(c => (c + 1).toChar) | |
| 740 | } | |
| 741 | ||
| 452 | 742 | "HAL".increment | 
| 325 | 743 | |
| 744 | ||
| 745 | // Abstract idea: | |
| 746 | // In that version implicit conversions were used to solve the | |
| 747 | // late extension problem; namely, given a class C and a class T, | |
| 748 | // how to have C extend T without touching or recompiling C. | |
| 749 | // Conversions add a wrapper when a member of T is requested | |
| 750 | // from an instance of C. | |
| 751 | ||
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 752 | |
| 325 | 753 | |
| 754 | import scala.concurrent.duration.{TimeUnit,SECONDS,MINUTES}
 | |
| 755 | ||
| 756 | case class Duration(time: Long, unit: TimeUnit) {
 | |
| 757 | def +(o: Duration) = | |
| 758 | Duration(time + unit.convert(o.time, o.unit), unit) | |
| 759 | } | |
| 760 | ||
| 761 | implicit class Int2Duration(that: Int) {
 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 762 | def seconds = Duration(that, SECONDS) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 763 | def minutes = Duration(that, MINUTES) | 
| 325 | 764 | } | 
| 765 | ||
| 766 | 5.seconds + 2.minutes //Duration(125L, SECONDS ) | |
| 767 | 2.minutes + 60.seconds | |
| 768 | ||
| 769 | ||
| 770 | ||
| 771 | ||
| 772 | // Regular expressions - the power of DSLs in Scala | |
| 773 | //================================================== | |
| 774 | ||
| 775 | abstract class Rexp | |
| 776 | case object ZERO extends Rexp // nothing | |
| 777 | case object ONE extends Rexp // the empty string | |
| 778 | case class CHAR(c: Char) extends Rexp // a character c | |
| 779 | case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative r1 + r2 | |
| 780 | case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence r1 . r2 | |
| 781 | case class STAR(r: Rexp) extends Rexp // star r* | |
| 782 | ||
| 783 | ||
| 784 | ||
| 785 | // writing (ab)* in the format above is | |
| 786 | // tedious | |
| 787 | val r0 = STAR(SEQ(CHAR('a'), CHAR('b')))
 | |
| 788 | ||
| 789 | ||
| 790 | // some convenience for typing in regular expressions | |
| 791 | import scala.language.implicitConversions | |
| 792 | import scala.language.reflectiveCalls | |
| 793 | ||
| 794 | def charlist2rexp(s: List[Char]): Rexp = s match {
 | |
| 795 | case Nil => ONE | |
| 796 | case c::Nil => CHAR(c) | |
| 797 | case c::s => SEQ(CHAR(c), charlist2rexp(s)) | |
| 798 | } | |
| 326 | 799 | |
| 325 | 800 | implicit def string2rexp(s: String): Rexp = | 
| 801 | charlist2rexp(s.toList) | |
| 802 | ||
| 415 | 803 | val r1 = STAR("ab")
 | 
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 804 | val r2 = STAR("hello") | STAR("world")
 | 
| 325 | 805 | |
| 806 | ||
| 807 | implicit def RexpOps (r: Rexp) = new {
 | |
| 808 | def | (s: Rexp) = ALT(r, s) | |
| 809 | def % = STAR(r) | |
| 810 | def ~ (s: Rexp) = SEQ(r, s) | |
| 811 | } | |
| 812 | ||
| 813 | implicit def stringOps (s: String) = new {
 | |
| 814 | def | (r: Rexp) = ALT(s, r) | |
| 815 | def | (r: String) = ALT(s, r) | |
| 816 | def % = STAR(s) | |
| 817 | def ~ (r: Rexp) = SEQ(s, r) | |
| 818 | def ~ (r: String) = SEQ(s, r) | |
| 819 | } | |
| 820 | ||
| 821 | //example regular expressions | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 822 | |
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 823 | |
| 326 | 824 | val digit = ("0" | "1" | "2" | "3" | "4" | 
 | 
| 825 | "5" | "6" | "7" | "8" | "9") | |
| 325 | 826 | val sign = "+" | "-" | "" | 
| 827 | val number = sign ~ digit ~ digit.% | |
| 828 | ||
| 829 | ||
| 830 | ||
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 831 | |
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 832 | // In mandelbrot.scala I used complex (imaginary) numbers | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 833 | // and implemented the usual arithmetic operations for complex | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 834 | // numbers. | 
| 325 | 835 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 836 | case class Complex(re: Double, im: Double) { 
 | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 837 | // represents the complex number re + im * i | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 838 | 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 | 839 | 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 | 840 | 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 | 841 | this.re * that.im + that.re * this.im) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 842 | def *(that: Double) = Complex(this.re * that, this.im * that) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 843 | 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 | 844 | } | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 845 | |
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 846 | val test = Complex(1, 2) + Complex (3, 4) | 
| 222 | 847 | |
| 325 | 848 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 849 | // ...to allow the notation n + m * i | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 850 | import scala.language.implicitConversions | 
| 325 | 851 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 852 | val i = Complex(0, 1) | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 853 | implicit def double2complex(re: Double) = Complex(re, 0) | 
| 222 | 854 | |
| 381 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 855 | val inum1 = -2.0 + -1.5 * i | 
| 
6c2792a3e00d
updated duration class
 Christian Urban <christian.urban@kcl.ac.uk> parents: 
380diff
changeset | 856 | val inum2 = 1.0 + 1.5 * i |