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