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