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