| author | Christian Urban <christian.urban@kcl.ac.uk> | 
| Fri, 02 Dec 2022 07:48:03 +0000 | |
| changeset 446 | 30b8f14b2655 | 
| parent 445 | 160cbb09027f | 
| child 478 | 0e6ca70496c1 | 
| permissions | -rw-r--r-- | 
| 67 | 1 | // Scala Lecture 3 | 
| 2 | //================= | |
| 3 | ||
| 446 | 4 | // - Higher-Order functions | 
| 445 | 5 | // - maps (behind for-comprehensions) | 
| 446 | 6 | |
| 445 | 7 | // - Pattern-Matching | 
| 8 | ||
| 446 | 9 | def fib(n: Int) : Int = n match {
 | 
| 10 | case 0 => 1 | |
| 11 | case 1 => 1 | |
| 12 | case n => fib(n - 1) + fib(n - 2) | |
| 13 | } | |
| 14 | ||
| 15 | ||
| 445 | 16 | abstract class Rexp | 
| 17 | case object ZERO extends Rexp // matches nothing | |
| 18 | case object ONE extends Rexp // matches the empty string | |
| 19 | case class CHAR(c: Char) extends Rexp // matches a character c | |
| 20 | case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative | |
| 21 | case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence | |
| 22 | case class STAR(r: Rexp) extends Rexp // star | |
| 23 | ||
| 24 | def depth(r: Rexp) : Int = r match {
 | |
| 25 | case ZERO => 1 | |
| 26 | case ONE => 1 | |
| 27 | case CHAR(_) => 1 | |
| 28 | case ALT(r1, r2) => 1 + List(depth(r1), depth(r2)).max | |
| 29 | case SEQ(r1, r2) => 1 + List(depth(r1), depth(r2)).max | |
| 30 | case STAR(r1) => 1 + depth(r1) | |
| 31 | } | |
| 32 | ||
| 33 | ||
| 34 | // - String-Interpolations | |
| 35 | ||
| 36 | // String Interpolations | |
| 37 | //======================= | |
| 38 | ||
| 39 | def cube(n: Int) : Int = n * n * n | |
| 40 | ||
| 41 | val n = 3 | |
| 42 | println("The cube of " + n + " is " + cube(n) + ".")
 | |
| 43 | ||
| 44 | println(s"The cube of $n is ${cube(n)}.")
 | |
| 45 | ||
| 46 | // or even | |
| 47 | ||
| 48 | println(s"The cube of $n is ${n * n * n}.")
 | |
| 49 | ||
| 50 | // helpful for debugging purposes | |
| 51 | // | |
| 52 | // "The most effective debugging tool is still careful | |
| 53 | // thought, coupled with judiciously placed print | |
| 54 | // statements." | |
| 55 | // — Brian W. Kernighan, in Unix for Beginners (1979) | |
| 56 | ||
| 57 | ||
| 58 | def gcd_db(a: Int, b: Int) : Int = {
 | |
| 59 | println(s"Function called with $a and $b.") | |
| 60 | if (b == 0) a else gcd_db(b, a % b) | |
| 61 | } | |
| 62 | ||
| 63 | gcd_db(48, 18) | |
| 320 | 64 | |
| 415 | 65 | |
| 343 | 66 | // naive quicksort with "On" function | 
| 67 | ||
| 68 | def sortOn(f: Int => Int, xs: List[Int]) : List[Int] = {
 | |
| 69 | if (xs.size < 2) xs | |
| 70 |   else {
 | |
| 71 | val pivot = xs.head | |
| 72 | val (left, right) = xs.partition(f(_) < f(pivot)) | |
| 73 | sortOn(f, left) ::: pivot :: sortOn(f, right.tail) | |
| 74 | } | |
| 75 | } | |
| 76 | ||
| 77 | sortOn(identity, List(99,99,99,98,10,-3,2)) | |
| 78 | sortOn(n => - n, List(99,99,99,98,10,-3,2)) | |
| 79 | ||
| 80 | ||
| 320 | 81 | // Recursion Again ;o) | 
| 82 | //==================== | |
| 83 | ||
| 217 | 84 | |
| 366 | 85 | // another well-known example: Towers of Hanoi | 
| 86 | //============================================= | |
| 178 | 87 | |
| 320 | 88 | def move(from: Char, to: Char) = | 
| 89 | println(s"Move disc from $from to $to!") | |
| 67 | 90 | |
| 320 | 91 | def hanoi(n: Int, from: Char, via: Char, to: Char) : Unit = {
 | 
| 92 | if (n == 0) () | |
| 93 |   else {
 | |
| 94 | hanoi(n - 1, from, to, via) | |
| 95 | move(from, to) | |
| 96 | hanoi(n - 1, via, from, to) | |
| 97 | } | |
| 98 | } | |
| 67 | 99 | |
| 320 | 100 | hanoi(4, 'A', 'B', 'C') | 
| 67 | 101 | |
| 155 | 102 | |
| 103 | ||
| 320 | 104 | // User-defined Datatypes | 
| 105 | //======================== | |
| 106 | ||
| 323 | 107 | abstract class Tree | 
| 108 | case class Leaf(x: Int) extends Tree | |
| 109 | case class Node(s: String, left: Tree, right: Tree) extends Tree | |
| 110 | ||
| 366 | 111 | val lf = Leaf(20) | 
| 112 | val tr = Node("foo", Leaf(10), Leaf(23))
 | |
| 320 | 113 | |
| 366 | 114 | val lst : List[Tree] = List(lf, tr) | 
| 115 | ||
| 116 | ||
| 117 | abstract class Colour | |
| 320 | 118 | case object Red extends Colour | 
| 119 | case object Green extends Colour | |
| 120 | case object Blue extends Colour | |
| 323 | 121 | case object Yellow extends Colour | 
| 320 | 122 | |
| 123 | ||
| 124 | def fav_colour(c: Colour) : Boolean = c match {
 | |
| 125 | case Green => true | |
| 323 | 126 | case _ => false | 
| 320 | 127 | } | 
| 128 | ||
| 366 | 129 | fav_colour(Blue) | 
| 130 | ||
| 320 | 131 | |
| 132 | // ... a tiny bit more useful: Roman Numerals | |
| 133 | ||
| 321 | 134 | sealed abstract class RomanDigit | 
| 320 | 135 | case object I extends RomanDigit | 
| 136 | case object V extends RomanDigit | |
| 137 | case object X extends RomanDigit | |
| 138 | case object L extends RomanDigit | |
| 139 | case object C extends RomanDigit | |
| 140 | case object D extends RomanDigit | |
| 141 | case object M extends RomanDigit | |
| 142 | ||
| 143 | type RomanNumeral = List[RomanDigit] | |
| 144 | ||
| 366 | 145 | List(X,I,M,A) | 
| 320 | 146 | |
| 147 | /* | |
| 148 | I -> 1 | |
| 149 | II -> 2 | |
| 150 | III -> 3 | |
| 151 | IV -> 4 | |
| 152 | V -> 5 | |
| 153 | VI -> 6 | |
| 154 | VII -> 7 | |
| 155 | VIII -> 8 | |
| 156 | IX -> 9 | |
| 157 | X -> 10 | |
| 158 | */ | |
| 159 | ||
| 160 | def RomanNumeral2Int(rs: RomanNumeral): Int = rs match { 
 | |
| 161 | case Nil => 0 | |
| 162 | case M::r => 1000 + RomanNumeral2Int(r) | |
| 163 | case C::M::r => 900 + RomanNumeral2Int(r) | |
| 164 | case D::r => 500 + RomanNumeral2Int(r) | |
| 165 | case C::D::r => 400 + RomanNumeral2Int(r) | |
| 166 | case C::r => 100 + RomanNumeral2Int(r) | |
| 167 | case X::C::r => 90 + RomanNumeral2Int(r) | |
| 168 | case L::r => 50 + RomanNumeral2Int(r) | |
| 169 | case X::L::r => 40 + RomanNumeral2Int(r) | |
| 170 | case X::r => 10 + RomanNumeral2Int(r) | |
| 171 | case I::X::r => 9 + RomanNumeral2Int(r) | |
| 172 | case V::r => 5 + RomanNumeral2Int(r) | |
| 173 | case I::V::r => 4 + RomanNumeral2Int(r) | |
| 174 | case I::r => 1 + RomanNumeral2Int(r) | |
| 175 | } | |
| 176 | ||
| 177 | RomanNumeral2Int(List(I,V)) // 4 | |
| 178 | RomanNumeral2Int(List(I,I,I,I)) // 4 (invalid Roman number) | |
| 179 | RomanNumeral2Int(List(V,I)) // 6 | |
| 180 | RomanNumeral2Int(List(I,X)) // 9 | |
| 181 | RomanNumeral2Int(List(M,C,M,L,X,X,I,X)) // 1979 | |
| 182 | RomanNumeral2Int(List(M,M,X,V,I,I)) // 2017 | |
| 183 | ||
| 184 | ||
| 366 | 185 | // expressions (essentially trees) | 
| 186 | ||
| 187 | abstract class Exp | |
| 188 | case class N(n: Int) extends Exp // for numbers | |
| 189 | case class Plus(e1: Exp, e2: Exp) extends Exp | |
| 190 | case class Times(e1: Exp, e2: Exp) extends Exp | |
| 191 | ||
| 192 | def string(e: Exp) : String = e match {
 | |
| 193 | case N(n) => s"$n" | |
| 194 |   case Plus(e1, e2) => s"(${string(e1)} + ${string(e2)})" 
 | |
| 195 |   case Times(e1, e2) => s"(${string(e1)} * ${string(e2)})"
 | |
| 196 | } | |
| 197 | ||
| 198 | val e = Plus(N(9), Times(N(3), N(4))) | |
| 199 | e.toString | |
| 200 | println(string(e)) | |
| 201 | ||
| 202 | def eval(e: Exp) : Int = e match {
 | |
| 203 | case N(n) => n | |
| 204 | case Plus(e1, e2) => eval(e1) + eval(e2) | |
| 205 | case Times(e1, e2) => eval(e1) * eval(e2) | |
| 206 | } | |
| 207 | ||
| 208 | println(eval(e)) | |
| 209 | ||
| 210 | // simplification rules: | |
| 211 | // e + 0, 0 + e => e | |
| 212 | // e * 0, 0 * e => 0 | |
| 213 | // e * 1, 1 * e => e | |
| 214 | // | |
| 215 | // (....9 ....) | |
| 216 | ||
| 217 | def simp(e: Exp) : Exp = e match {
 | |
| 218 | case N(n) => N(n) | |
| 219 |   case Plus(e1, e2) => (simp(e1), simp(e2)) match {
 | |
| 220 | case (N(0), e2s) => e2s | |
| 221 | case (e1s, N(0)) => e1s | |
| 222 | case (e1s, e2s) => Plus(e1s, e2s) | |
| 223 | } | |
| 224 |   case Times(e1, e2) => (simp(e1), simp(e2)) match {
 | |
| 225 | case (N(0), _) => N(0) | |
| 226 | case (_, N(0)) => N(0) | |
| 227 | case (N(1), e2s) => e2s | |
| 228 | case (e1s, N(1)) => e1s | |
| 229 | case (e1s, e2s) => Times(e1s, e2s) | |
| 230 | } | |
| 231 | } | |
| 232 | ||
| 233 | ||
| 234 | val e2 = Times(Plus(N(0), N(1)), Plus(N(0), N(9))) | |
| 235 | println(string(e2)) | |
| 236 | println(string(simp(e2))) | |
| 237 | ||
| 238 | ||
| 239 | ||
| 320 | 240 | // String interpolations as patterns | 
| 241 | ||
| 242 | val date = "2019-11-26" | |
| 243 | val s"$year-$month-$day" = date | |
| 244 | ||
| 245 | def parse_date(date: String) : Option[(Int, Int, Int)]= date match {
 | |
| 246 | case s"$year-$month-$day" => Some((day.toInt, month.toInt, year.toInt)) | |
| 247 | case s"$day/$month/$year" => Some((day.toInt, month.toInt, year.toInt)) | |
| 248 | case s"$day.$month.$year" => Some((day.toInt, month.toInt, year.toInt)) | |
| 249 | case _ => None | |
| 250 | } | |
| 318 | 251 | |
| 320 | 252 | parse_date("2019-11-26")
 | 
| 253 | parse_date("26/11/2019")
 | |
| 254 | parse_date("26.11.2019")
 | |
| 255 | ||
| 256 | ||
| 374 | 257 | // guards in pattern-matching | 
| 320 | 258 | |
| 374 | 259 | def foo(xs: List[Int]) : String = xs match {
 | 
| 260 | case Nil => s"this list is empty" | |
| 261 | case x :: xs if x % 2 == 0 | |
| 262 | => s"the first elemnt is even" | |
| 263 | case x :: y :: rest if x == y | |
| 264 | => s"this has two elemnts that are the same" | |
| 265 | case hd :: tl => s"this list is standard $hd::$tl" | |
| 266 | } | |
| 320 | 267 | |
| 374 | 268 | foo(Nil) | 
| 269 | foo(List(1,2,3)) | |
| 270 | foo(List(1,2)) | |
| 271 | foo(List(1,1,2,3)) | |
| 272 | foo(List(2,2,2,3)) | |
| 320 | 273 | |
| 274 | // Tail recursion | |
| 275 | //================ | |
| 276 | ||
| 375 | 277 | def fact(n: BigInt): BigInt = | 
| 320 | 278 | if (n == 0) 1 else n * fact(n - 1) | 
| 279 | ||
| 280 | fact(10) //ok | |
| 281 | fact(10000) // produces a stackoverflow | |
| 282 | ||
| 375 | 283 | |
| 320 | 284 | def factT(n: BigInt, acc: BigInt): BigInt = | 
| 285 | if (n == 0) acc else factT(n - 1, n * acc) | |
| 286 | ||
| 287 | factT(10, 1) | |
| 288 | println(factT(100000, 1)) | |
| 289 | ||
| 290 | // there is a flag for ensuring a function is tail recursive | |
| 291 | import scala.annotation.tailrec | |
| 292 | ||
| 293 | @tailrec | |
| 294 | def factT(n: BigInt, acc: BigInt): BigInt = | |
| 295 | if (n == 0) acc else factT(n - 1, n * acc) | |
| 296 | ||
| 297 | ||
| 298 | ||
| 299 | // for tail-recursive functions the Scala compiler | |
| 300 | // generates loop-like code, which does not need | |
| 301 | // to allocate stack-space in each recursive | |
| 302 | // call; Scala can do this only for tail-recursive | |
| 303 | // functions | |
| 304 | ||
| 375 | 305 | def length(xs: List[Int]) : Int = xs match {
 | 
| 306 | case Nil => 0 | |
| 307 | case _ :: tail => 1 + length(tail) | |
| 308 | } | |
| 366 | 309 | |
| 375 | 310 | @tailrec | 
| 311 | def lengthT(xs: List[Int], acc : Int) : Int = xs match {
 | |
| 312 | case Nil => acc | |
| 313 | case _ :: tail => lengthT(tail, 1 + acc) | |
| 314 | } | |
| 315 | ||
| 316 | lengthT(List.fill(10000000)(1), 0) | |
| 366 | 317 | |
| 318 | ||
| 319 | // Sudoku | |
| 320 | //======== | |
| 321 | ||
| 446 | 322 | // uses Strings for games | 
| 366 | 323 | |
| 324 | type Pos = (Int, Int) | |
| 325 | val emptyValue = '.' | |
| 326 | val maxValue = 9 | |
| 327 | ||
| 328 | val allValues = "123456789".toList | |
| 329 | val indexes = (0 to 8).toList | |
| 330 | ||
| 331 | ||
| 332 | def empty(game: String) = game.indexOf(emptyValue) | |
| 333 | def isDone(game: String) = empty(game) == -1 | |
| 334 | def emptyPosition(game: String) : Pos = | |
| 335 | (empty(game) % maxValue, empty(game) / maxValue) | |
| 336 | ||
| 337 | ||
| 338 | def get_row(game: String, y: Int) = indexes.map(col => game(y * maxValue + col)) | |
| 339 | def get_col(game: String, x: Int) = indexes.map(row => game(x + row * maxValue)) | |
| 340 | ||
| 341 | def get_box(game: String, pos: Pos): List[Char] = {
 | |
| 342 | def base(p: Int): Int = (p / 3) * 3 | |
| 343 | val x0 = base(pos._1) | |
| 344 | val y0 = base(pos._2) | |
| 345 | for (x <- (x0 until x0 + 3).toList; | |
| 346 | y <- (y0 until y0 + 3).toList) yield game(x + y * maxValue) | |
| 347 | } | |
| 348 | ||
| 349 | ||
| 350 | def update(game: String, pos: Int, value: Char): String = | |
| 351 | game.updated(pos, value) | |
| 352 | ||
| 353 | def toAvoid(game: String, pos: Pos): List[Char] = | |
| 354 | (get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos)) | |
| 355 | ||
| 356 | def candidates(game: String, pos: Pos): List[Char] = | |
| 357 | allValues.diff(toAvoid(game, pos)) | |
| 358 | ||
| 359 | def search(game: String): List[String] = {
 | |
| 360 | if (isDone(game)) List(game) | |
| 361 | else | |
| 446 | 362 | candidates(game, emptyPosition(game)). | 
| 363 | map(c => search(update(game, empty(game), c))).flatten | |
| 366 | 364 | } | 
| 365 | ||
| 375 | 366 | |
| 366 | 367 | def search1T(games: List[String]): Option[String] = games match {
 | 
| 368 | case Nil => None | |
| 369 |   case game::rest => {
 | |
| 370 | if (isDone(game)) Some(game) | |
| 371 |     else {
 | |
| 372 | val cs = candidates(game, emptyPosition(game)) | |
| 373 | search1T(cs.map(c => update(game, empty(game), c)) ::: rest) | |
| 374 | } | |
| 375 | } | |
| 376 | } | |
| 377 | ||
| 378 | def pretty(game: String): String = | |
| 379 |   "\n" + (game.sliding(maxValue, maxValue).mkString(",\n"))
 | |
| 380 | ||
| 381 | ||
| 155 | 382 | // tail recursive version that searches | 
| 158 | 383 | // for all solutions | 
| 384 | ||
| 155 | 385 | def searchT(games: List[String], sols: List[String]): List[String] = games match {
 | 
| 386 | case Nil => sols | |
| 387 |   case game::rest => {
 | |
| 388 | if (isDone(game)) searchT(rest, game::sols) | |
| 389 |     else {
 | |
| 390 | val cs = candidates(game, emptyPosition(game)) | |
| 391 | searchT(cs.map(c => update(game, empty(game), c)) ::: rest, sols) | |
| 392 | } | |
| 393 | } | |
| 67 | 394 | } | 
| 395 | ||
| 158 | 396 | searchT(List(game3), List()).map(pretty) | 
| 397 | ||
| 398 | ||
| 155 | 399 | // tail recursive version that searches | 
| 400 | // for a single solution | |
| 158 | 401 | |
| 155 | 402 | def search1T(games: List[String]): Option[String] = games match {
 | 
| 67 | 403 | case Nil => None | 
| 155 | 404 |   case game::rest => {
 | 
| 405 | if (isDone(game)) Some(game) | |
| 406 |     else {
 | |
| 407 | val cs = candidates(game, emptyPosition(game)) | |
| 408 | search1T(cs.map(c => update(game, empty(game), c)) ::: rest) | |
| 409 | } | |
| 410 | } | |
| 67 | 411 | } | 
| 412 | ||
| 158 | 413 | search1T(List(game3)).map(pretty) | 
| 217 | 414 | time_needed(10, search1T(List(game3))) | 
| 415 | ||
| 158 | 416 | |
| 155 | 417 | // game with multiple solutions | 
| 418 | val game3 = """.8...9743 | |
| 419 | |.5...8.1. | |
| 420 | |.1....... | |
| 421 | |8....5... | |
| 422 | |...8.4... | |
| 423 | |...3....6 | |
| 424 | |.......7. | |
| 425 | |.3.5...8. | |
| 426 |               |9724...5.""".stripMargin.replaceAll("\\n", "")
 | |
| 427 | ||
| 158 | 428 | searchT(List(game3), Nil).map(pretty) | 
| 155 | 429 | search1T(List(game3)).map(pretty) | 
| 67 | 430 | |
| 77 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 431 | // Moral: Whenever a recursive function is resource-critical | 
| 158 | 432 | // (i.e. works with large recursion depth), then you need to | 
| 77 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 433 | // write it in tail-recursive fashion. | 
| 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 434 | // | 
| 155 | 435 | // Unfortuantely, Scala because of current limitations in | 
| 436 | // the JVM is not as clever as other functional languages. It can | |
| 77 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 437 | // only optimise "self-tail calls". This excludes the cases of | 
| 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 438 | // multiple functions making tail calls to each other. Well, | 
| 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 439 | // nothing is perfect. | 
| 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 440 |