| author | Christian Urban <christian.urban@kcl.ac.uk> |
| Fri, 05 Dec 2025 10:20:00 +0000 | |
| changeset 506 | 28f78d9081d7 |
| parent 491 | 2a30c7dfe3ed |
| permissions | -rw-r--r-- |
| 67 | 1 |
// Scala Lecture 3 |
2 |
//================= |
|
3 |
||
| 478 | 4 |
// last week: |
5 |
// higher-order functions |
|
6 |
// maps |
|
| 506 | 7 |
// recursion |
| 446 | 8 |
|
| 506 | 9 |
|
| 445 | 10 |
// - Pattern-Matching |
| 506 | 11 |
// - Datatypes |
12 |
// - Countdown Game |
|
13 |
// - String interpolations |
|
14 |
||
| 445 | 15 |
|
| 491 | 16 |
def fact(n: BigInt) : BigInt = {
|
17 |
if (n == 0) 1 |
|
18 |
else n * fact(n - 1) |
|
19 |
} |
|
20 |
||
21 |
def fib(n: BigInt) : BigInt = {
|
|
22 |
if (n == 0) 1 |
|
23 |
else if (n == 1) 1 |
|
24 |
else fib(n - 1) + fib(n - 2) |
|
25 |
} |
|
26 |
||
| 506 | 27 |
def list_len(xs: List[Int]) : Int = |
28 |
if (xs == Nil) 0 |
|
29 |
else 1 + list_len(xs.tail) |
|
30 |
||
31 |
def list_len(xs: List[Int]) : Int = xs match {
|
|
32 |
case Nil => 0 |
|
33 |
case _::xt => 1 + list_len(xt) |
|
34 |
} |
|
35 |
||
36 |
def list_len(xs: List[Int]) : Int = |
|
37 |
if (xs == Nil) 0 |
|
38 |
else 1 + list_len(xs.tail) |
|
39 |
||
40 |
||
41 |
def list_map(xs: List[Int], f: Int => Int) : List[Int] = |
|
42 |
if (xs == Nil) Nil |
|
43 |
else f(xs.head) :: list_map(xs.tail, f) |
|
| 491 | 44 |
|
45 |
||
46 |
||
| 506 | 47 |
def altproduct(xs: List[Int]) : List[Int] = xs match {
|
48 |
case Nil => Nil |
|
49 |
case (x::y::xs) => x * y :: altproduct(y::xs) |
|
50 |
case (x::Nil) => List(x) |
|
51 |
} |
|
52 |
||
53 |
altproduct(List(1,2,3,4,5)) |
|
54 |
||
55 |
||
56 |
def powerset(xs: Set[Int]) : Set[Set[Int]] = {
|
|
57 |
if (xs == Set()) Set(Set()) |
|
58 |
else {
|
|
59 |
val ps = powerset(xs.tail) |
|
60 |
ps ++ ps.map(_ + xs.head) |
|
61 |
} |
|
62 |
} |
|
63 |
||
64 |
powerset(Set(1,2,3)).mkString("\n")
|
|
65 |
||
| 491 | 66 |
|
67 |
def inc(n: Int) : Int = n + 1 |
|
68 |
||
69 |
for (n <- List(1,2,3,4)) yield inc(n) |
|
70 |
||
71 |
List().map(inc) |
|
72 |
||
73 |
||
74 |
||
75 |
my_map(inc, List(1,2,3,4)) |
|
76 |
||
77 |
||
78 |
||
| 506 | 79 |
// Pattern Matching |
80 |
//================== |
|
81 |
||
82 |
// A powerful tool which has even landed in Java during |
|
83 |
// the last few years (https://inside.java/2021/06/13/podcast-017/). |
|
84 |
// ...Scala already has it for many years and the concept is |
|
85 |
// older than your friendly lecturer, that is stone old ;o) |
|
86 |
||
87 |
// The general schema: |
|
88 |
// |
|
89 |
// expression match {
|
|
90 |
// case pattern1 => expression1 |
|
91 |
// case pattern2 => expression2 |
|
92 |
// ... |
|
93 |
// case patternN => expressionN |
|
94 |
// } |
|
95 |
||
96 |
def my_map(f: Int => Int, xs: List[Int]) : List[Int] = |
|
97 |
xs match {
|
|
98 |
case Nil => Nil |
|
99 |
case hd::tl => f(hd) :: my_map(f, tl) |
|
100 |
} |
|
101 |
||
102 |
my_map(x => x * x, List(1,2,3,4)) |
|
103 |
||
104 |
||
105 |
// recall |
|
106 |
def len(xs: List[Int]) : Int = {
|
|
107 |
if (xs == Nil) 0 |
|
108 |
else 1 + len(xs.tail) |
|
109 |
} |
|
110 |
||
111 |
def len(xs: List[Int]) : Int = xs match {
|
|
112 |
case Nil => 0 |
|
113 |
case hd::tail => 1 + len(tail) |
|
114 |
} |
|
115 |
||
116 |
||
117 |
def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = |
|
118 |
lst match {
|
|
119 |
case Nil => Nil |
|
120 |
case x::xs => f(x)::my_map_int(xs, f) |
|
121 |
} |
|
122 |
||
123 |
def my_map_option(opt: Option[Int], f: Int => Int) : Option[Int] = |
|
124 |
opt match {
|
|
125 |
case None => None |
|
126 |
case Some(x) => Some(f(x)) |
|
127 |
} |
|
128 |
||
129 |
my_map_option(None, x => x * x) |
|
130 |
my_map_option(Some(8), x => x * x) |
|
131 |
||
132 |
||
133 |
// you can also have cases combined |
|
134 |
def season(month: String) : String = month match {
|
|
135 |
case "March" | "April" | "May" => "It's spring" |
|
136 |
case "June" | "July" | "August" => "It's summer" |
|
137 |
case "September" | "October" | "November" => "It's autumn" |
|
138 |
case "December" => "It's winter" |
|
139 |
case "January" | "February" => "It's unfortunately winter" |
|
140 |
case _ => "Wrong month" |
|
141 |
} |
|
142 |
||
143 |
||
144 |
season("November")
|
|
145 |
season("abcd")
|
|
146 |
// pattern-match on integers |
|
147 |
||
148 |
def fib(n: Int) : Int = n match {
|
|
149 |
case 0 | 1 => 1 |
|
150 |
case n => fib(n - 1) + fib(n - 2) |
|
151 |
} |
|
152 |
||
153 |
fib(10) |
|
154 |
||
155 |
// pattern-match on results |
|
156 |
||
157 |
// Silly: fizz buzz |
|
158 |
def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
|
|
159 |
case (0, 0) => "fizz buzz" |
|
160 |
case (0, _) => "fizz" |
|
161 |
case (_, 0) => "buzz" |
|
162 |
case _ => n.toString |
|
163 |
} |
|
164 |
||
165 |
for (n <- 1 to 20) |
|
166 |
println(fizz_buzz(n)) |
|
167 |
||
168 |
// more interesting patterns for lists - calculate the deltas between |
|
169 |
// elements |
|
170 |
||
171 |
List(4,3,2,1) -> List(1,1,.. ) |
|
172 |
||
173 |
def delta(xs: List[Int]) : List[Int] = xs match {
|
|
174 |
case Nil => Nil |
|
175 |
case x::Nil => x::Nil |
|
176 |
case x::y::xs => (x - y)::delta(y::xs) |
|
177 |
} |
|
178 |
||
179 |
delta(List(10, 7, 8, 2, 5, 10)) |
|
180 |
||
181 |
||
182 |
// guards in pattern-matching |
|
183 |
||
184 |
def foo(xs: List[Int]) : String = xs match {
|
|
185 |
case Nil => s"this list is empty" |
|
186 |
case x :: xs if x % 2 == 0 |
|
187 |
=> s"the first elemnt is even" |
|
188 |
case x :: y :: rest if x == y |
|
189 |
=> s"this has two elemnts that are the same" |
|
190 |
case hd :: tl => s"this list is standard $hd::$tl" |
|
191 |
} |
|
192 |
||
193 |
foo(Nil) |
|
194 |
foo(List(1,2,3)) |
|
195 |
foo(List(1,2)) |
|
196 |
foo(List(1,1,2,3)) |
|
197 |
foo(List(2,2,2,3)) |
|
198 |
||
199 |
||
200 |
// Trees |
|
201 |
||
202 |
enum Tree {
|
|
203 |
case Leaf(x: Int) |
|
204 |
case Node(s: String, left: Tree, right: Tree) |
|
205 |
} |
|
206 |
import Tree._ |
|
207 |
||
208 |
val lf = Leaf(20) |
|
209 |
val tr = Node("foo", Leaf(10), Leaf(23))
|
|
210 |
||
211 |
def tree_size(t: Tree) : Int = t match {
|
|
212 |
case Leaf(_) => 1 |
|
213 |
case Node(_, left , right) => |
|
214 |
1 + tree_size(left) + tree_size(right) |
|
215 |
} |
|
216 |
||
217 |
tree_size(tr) |
|
218 |
||
219 |
val lst : List[Tree] = List(lf, tr) |
|
220 |
||
221 |
||
222 |
abstract class Colour |
|
223 |
case object Red extends Colour |
|
224 |
case object Green extends Colour |
|
225 |
case object Blue extends Colour |
|
226 |
case object Yellow extends Colour |
|
227 |
||
228 |
||
229 |
def fav_colour(c: Colour) : Boolean = c match {
|
|
230 |
case Green => true |
|
231 |
case _ => false |
|
232 |
} |
|
233 |
||
234 |
fav_colour(Blue) |
|
235 |
||
236 |
enum ChessPiece: |
|
237 |
case Queen, Rook, Bishop, Knight, Pawn |
|
238 |
def value = this match |
|
239 |
case Queen => 9 |
|
240 |
case Rook => 5 |
|
241 |
case Bishop => 3 |
|
242 |
case Knight => 3 |
|
243 |
case Pawn => 1 |
|
244 |
||
245 |
||
246 |
||
247 |
// ... a tiny bit more useful: Roman Numerals |
|
248 |
||
249 |
sealed abstract class RomanDigit |
|
250 |
case object I extends RomanDigit |
|
251 |
case object V extends RomanDigit |
|
252 |
case object X extends RomanDigit |
|
253 |
case object L extends RomanDigit |
|
254 |
case object C extends RomanDigit |
|
255 |
case object D extends RomanDigit |
|
256 |
case object M extends RomanDigit |
|
257 |
||
258 |
type RomanNumeral = List[RomanDigit] |
|
259 |
||
260 |
List(X,I,M,A) |
|
261 |
||
262 |
/* |
|
263 |
I -> 1 |
|
264 |
II -> 2 |
|
265 |
III -> 3 |
|
266 |
IV -> 4 |
|
267 |
V -> 5 |
|
268 |
VI -> 6 |
|
269 |
VII -> 7 |
|
270 |
VIII -> 8 |
|
271 |
IX -> 9 |
|
272 |
X -> 10 |
|
273 |
*/ |
|
274 |
||
275 |
def RomanNumeral2Int(rs: RomanNumeral): Int = rs match {
|
|
276 |
case Nil => 0 |
|
277 |
case M::r => 1000 + RomanNumeral2Int(r) |
|
278 |
case C::M::r => 900 + RomanNumeral2Int(r) |
|
279 |
case D::r => 500 + RomanNumeral2Int(r) |
|
280 |
case C::D::r => 400 + RomanNumeral2Int(r) |
|
281 |
case C::r => 100 + RomanNumeral2Int(r) |
|
282 |
case X::C::r => 90 + RomanNumeral2Int(r) |
|
283 |
case L::r => 50 + RomanNumeral2Int(r) |
|
284 |
case X::L::r => 40 + RomanNumeral2Int(r) |
|
285 |
case X::r => 10 + RomanNumeral2Int(r) |
|
286 |
case I::X::r => 9 + RomanNumeral2Int(r) |
|
287 |
case V::r => 5 + RomanNumeral2Int(r) |
|
288 |
case I::V::r => 4 + RomanNumeral2Int(r) |
|
289 |
case I::r => 1 + RomanNumeral2Int(r) |
|
290 |
} |
|
291 |
||
292 |
RomanNumeral2Int(List(I,V)) // 4 |
|
293 |
RomanNumeral2Int(List(I,I,I,I)) // 4 (invalid Roman number) |
|
294 |
RomanNumeral2Int(List(V,I)) // 6 |
|
295 |
RomanNumeral2Int(List(I,X)) // 9 |
|
296 |
RomanNumeral2Int(List(M,C,M,L,X,X,I,X)) // 1979 |
|
297 |
RomanNumeral2Int(List(M,M,X,V,I,I)) // 2017 |
|
298 |
||
299 |
||
300 |
abstract class Rexp |
|
301 |
case object ZERO extends Rexp // matches nothing |
|
302 |
case object ONE extends Rexp // matches the empty string |
|
303 |
case class CHAR(c: Char) extends Rexp // matches a character c |
|
304 |
case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative |
|
305 |
case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence |
|
306 |
case class STAR(r: Rexp) extends Rexp // star |
|
307 |
||
308 |
def depth(r: Rexp) : Int = r match {
|
|
309 |
case ZERO => 1 |
|
310 |
case ONE => 1 |
|
311 |
case CHAR(_) => 1 |
|
312 |
case ALT(r1, r2) => 1 + List(depth(r1), depth(r2)).max |
|
313 |
case SEQ(r1, r2) => 1 + List(depth(r1), depth(r2)).max |
|
314 |
case STAR(r1) => 1 + depth(r1) |
|
315 |
} |
|
316 |
||
317 |
||
| 491 | 318 |
|
319 |
||
320 |
||
| 506 | 321 |
// expressions (essentially trees) |
322 |
||
323 |
abstract class Exp |
|
324 |
case class N(n: Int) extends Exp // for numbers |
|
325 |
case class Plus(e1: Exp, e2: Exp) extends Exp |
|
326 |
case class Times(e1: Exp, e2: Exp) extends Exp |
|
327 |
||
328 |
def string(e: Exp) : String = e match {
|
|
329 |
case N(n) => s"$n" |
|
330 |
case Plus(e1, e2) => s"(${string(e1)} + ${string(e2)})"
|
|
331 |
case Times(e1, e2) => s"(${string(e1)} * ${string(e2)})"
|
|
332 |
} |
|
333 |
||
334 |
val e = Plus(N(9), Times(N(3), N(4))) |
|
335 |
e.toString |
|
336 |
println(string(e)) |
|
337 |
||
338 |
def eval(e: Exp) : Int = e match {
|
|
339 |
case N(n) => n |
|
340 |
case Plus(e1, e2) => eval(e1) + eval(e2) |
|
341 |
case Times(e1, e2) => eval(e1) * eval(e2) |
|
342 |
} |
|
| 478 | 343 |
|
| 506 | 344 |
println(eval(e)) |
345 |
||
346 |
// simplification rules: |
|
347 |
// e + 0, 0 + e => e |
|
348 |
// e * 0, 0 * e => 0 |
|
349 |
// e * 1, 1 * e => e |
|
350 |
// |
|
351 |
// (....9 ....) |
|
| 478 | 352 |
|
| 506 | 353 |
def simp(e: Exp) : Exp = e match {
|
354 |
case N(n) => N(n) |
|
355 |
case Plus(e1, e2) => (simp(e1), simp(e2)) match {
|
|
356 |
case (N(0), e2s) => e2s |
|
357 |
case (e1s, N(0)) => e1s |
|
358 |
case (e1s, e2s) => Plus(e1s, e2s) |
|
359 |
} |
|
360 |
case Times(e1, e2) => (simp(e1), simp(e2)) match {
|
|
361 |
case (N(0), _) => N(0) |
|
362 |
case (_, N(0)) => N(0) |
|
363 |
case (N(1), e2s) => e2s |
|
364 |
case (e1s, N(1)) => e1s |
|
365 |
case (e1s, e2s) => Times(e1s, e2s) |
|
366 |
} |
|
| 478 | 367 |
} |
368 |
||
| 506 | 369 |
|
370 |
val e2 = Times(Plus(N(0), N(1)), Plus(N(0), N(9))) |
|
371 |
println(string(e2)) |
|
372 |
println(string(simp(e2))) |
|
373 |
||
374 |
||
375 |
||
376 |
// String interpolations as patterns |
|
377 |
||
378 |
val date = "2019-11-26" |
|
379 |
val s"$year-$month-$day" = date |
|
380 |
||
381 |
def parse_date(date: String) : Option[(Int, Int, Int)]= date match {
|
|
382 |
case s"$year-$month-$day" => Some((day.toInt, month.toInt, year.toInt)) |
|
383 |
case s"$day/$month/$year" => Some((day.toInt, month.toInt, year.toInt)) |
|
384 |
case s"$day.$month.$year" => Some((day.toInt, month.toInt, year.toInt)) |
|
385 |
case _ => None |
|
386 |
} |
|
387 |
||
388 |
parse_date("2019-11-26")
|
|
389 |
parse_date("26/11/2019")
|
|
390 |
parse_date("26.11.2019")
|
|
391 |
||
| 478 | 392 |
|
| 506 | 393 |
// Countdown Game using Powerset |
394 |
//=============================== |
|
395 |
||
396 |
||
397 |
def powerset(xs: Set[Int]) : Set[Set[Int]] = {
|
|
398 |
if (xs == Set()) Set(Set()) |
|
399 |
else {
|
|
400 |
val ps = powerset(xs.tail) |
|
401 |
ps ++ ps.map(_ + xs.head) |
|
402 |
} |
|
403 |
} |
|
404 |
||
405 |
powerset(Set(1,2,3)).mkString("\n")
|
|
406 |
||
407 |
// proper subsets |
|
408 |
def psubsets(xs: Set[Int]) = |
|
409 |
powerset(xs) -- Set(Set(), xs) |
|
410 |
||
411 |
psubsets(Set(1,2,3)).mkString("\n")
|
|
412 |
||
413 |
def splits(xs: Set[Int]) : Set[(Set[Int], Set[Int])] = |
|
414 |
psubsets(xs).map(s => (s, xs -- s)) |
|
415 |
||
416 |
splits(Set(1,2,3,4)).mkString("\n")
|
|
| 478 | 417 |
|
418 |
||
| 506 | 419 |
enum Tree {
|
420 |
case Num(i: Int) |
|
421 |
case Add(l: Tree, r: Tree) |
|
422 |
case Mul(l: Tree, r: Tree) |
|
423 |
case Sub(l: Tree, r: Tree) |
|
424 |
case Div(l: Tree, r: Tree) |
|
425 |
} |
|
426 |
import Tree._ |
|
| 478 | 427 |
|
| 506 | 428 |
//pretty printing |
429 |
def pp(tr: Tree) : String = tr match {
|
|
430 |
case Num(n) => s"$n" |
|
431 |
case Add(l, r) => s"(${pp(l)} + ${pp(r)})"
|
|
432 |
case Mul(l, r) => s"(${pp(l)} * ${pp(r)})"
|
|
433 |
case Sub(l, r) => s"(${pp(l)} - ${pp(r)})"
|
|
434 |
case Div(l, r) => s"(${pp(l)} / ${pp(r)})"
|
|
435 |
} |
|
436 |
||
| 478 | 437 |
|
| 506 | 438 |
def eval(tr: Tree) : Option[Int] = tr match {
|
439 |
case Num(n) => Some(n) |
|
440 |
case Add(l, r) => |
|
441 |
for (ln <- eval(l); rn <- eval(r)) yield ln + rn |
|
442 |
case Mul(l, r) => |
|
443 |
for (ln <- eval(l); rn <- eval(r)) yield ln * rn |
|
444 |
case Sub(l, r) => |
|
445 |
for (ln <- eval(l); rn <- eval(r)) yield ln - rn |
|
446 |
case Div(l, r) => |
|
447 |
for (ln <- eval(l); rn <- eval(r); if rn != 0) |
|
448 |
yield ln / rn |
|
449 |
} |
|
450 |
||
451 |
||
452 |
||
453 |
def search(nums: Set[Int]) : Set[Tree] = nums.size match {
|
|
454 |
case 0 => Set() |
|
455 |
case 1 => Set(Num(nums.head)) |
|
456 |
case 2 => {
|
|
457 |
val ln = Num(nums.head) |
|
458 |
val rn = Num(nums.tail.head) |
|
459 |
Set(Add(ln, rn), Mul(ln, rn), |
|
460 |
Sub(ln, rn), Sub(rn, ln), |
|
461 |
Div(ln, rn), Div(rn, ln)) |
|
462 |
} |
|
463 |
case n => {
|
|
464 |
val spls = splits(nums) |
|
465 |
val res = |
|
466 |
for ((ls, rs) <- spls) yield {
|
|
467 |
for (lt <- search(ls); |
|
468 |
rt <- search(rs)) yield {
|
|
469 |
Set(Add(lt, rt), Mul(lt, rt), |
|
470 |
Sub(lt, rt), Sub(rt, lt), |
|
471 |
Div(lt, rt), Div(rt, lt)) |
|
472 |
} |
|
473 |
} |
|
474 |
res.flatten.flatten |
|
| 478 | 475 |
} |
476 |
} |
|
477 |
||
| 506 | 478 |
Set(Set(1,2), Set(2,3), Set(4,5)).flatten |
479 |
||
480 |
search(Set(1)) |
|
481 |
search(Set(1, 2)).mkString("\n")
|
|
482 |
search(Set(1, 2,3)).map(pp).mkString("\n")
|
|
483 |
search(Set(1, 2,3)).map(pl).mkString("\n")
|
|
484 |
search(Set(1, 2,3)).map(tr => s"${pp(tr)} = ${eval(tr)}").mkString("\n")
|
|
485 |
||
| 478 | 486 |
|
| 506 | 487 |
def search(nums: Set[Int]) : Set[Tree] = nums.size match {
|
488 |
case 0 => Set() |
|
489 |
case 1 => Set(Num(nums.head)) |
|
490 |
case xs => {
|
|
491 |
val spls = splits(nums) |
|
492 |
val subtrs = |
|
493 |
for ((lspls, rspls) <- spls; |
|
494 |
lt <- search(lspls); |
|
495 |
rt <- search(rspls)) yield {
|
|
496 |
Set(Add(lt, rt), Mul(lt, rt)) |
|
497 |
} |
|
498 |
subtrs.flatten |
|
499 |
} |
|
500 |
} |
|
501 |
||
502 |
println(search(Set(1,2,3,4)).mkString("\n"))
|
|
503 |
||
504 |
def pp(tr: Tree) : String = tr match {
|
|
505 |
case Num(n) => s"$n" |
|
506 |
case Add(l, r) => s"(${pp(l)} + ${pp(r)})"
|
|
507 |
case Mul(l, r) => s"(${pp(l)} * ${pp(r)})"
|
|
508 |
} |
|
509 |
||
| 478 | 510 |
|
511 |
||
| 506 | 512 |
def eval(tr: Tree) : Int = tr match {
|
513 |
case Num(n) => n |
|
514 |
case Add(l, r) => eval(l) + eval(r) |
|
515 |
case Mul(l, r) => eval(l) * eval(r) |
|
516 |
} |
|
517 |
||
518 |
||
519 |
||
520 |
||
521 |
||
522 |
def search(nums: Set[Int]) : Set[Tree] = nums.size match {
|
|
523 |
case 0 => Set() |
|
524 |
case 1 => Set(Num(nums.head)) |
|
525 |
case 2 => {
|
|
526 |
val l = nums.head |
|
527 |
val r = nums.tail.head |
|
528 |
Set(Add(Num(l), Num(r)), |
|
529 |
Mul(Num(l), Num(r))) |
|
530 |
++ Option.when(l <= r)(Sub(Num(r), Num(l))) |
|
531 |
++ Option.when(l > r)(Sub(Num(l), Num(r))) |
|
532 |
++ Option.when(r > 0 && l % r == 0)(Div(Num(l), Num(r))) |
|
533 |
++ Option.when(l > 0 && r % l == 0)(Div(Num(r), Num(l))) |
|
534 |
} |
|
535 |
case xs => {
|
|
536 |
val spls = splits(nums) |
|
537 |
val subtrs = |
|
538 |
for ((lspls, rspls) <- spls; |
|
539 |
lt <- search(lspls); |
|
540 |
rt <- search(rspls)) yield {
|
|
541 |
Set(Add(lt, rt), Sub(lt, rt), |
|
542 |
Mul(lt, rt), Div(lt, rt)) |
|
543 |
} |
|
544 |
subtrs.flatten |
|
| 478 | 545 |
} |
546 |
} |
|
547 |
||
| 506 | 548 |
println(search(Set(1,2,3,4)).mkString("\n"))
|
549 |
||
550 |
def eval(tr: Tree) : Option[Int] = tr match {
|
|
551 |
case Num(n) => Some(n) |
|
552 |
case Add(l, r) => |
|
553 |
for (rl <- eval(l); rr <- eval(r)) yield rl + rr |
|
554 |
case Mul(l, r) => |
|
555 |
for (rl <- eval(l); rr <- eval(r)) yield rl * rr |
|
556 |
case Sub(l, r) => |
|
557 |
for (rl <- eval(l); rr <- eval(r); |
|
558 |
if 0 <= rl - rr) yield rl - rr |
|
559 |
case Div(l, r) => |
|
560 |
for (rl <- eval(l); rr <- eval(r); |
|
561 |
if rr > 0 && rl % rr == 0) yield rl / rr |
|
562 |
} |
|
563 |
||
564 |
eval(Add(Num(1), Num(2))) |
|
565 |
eval(Mul(Add(Num(1), Num(2)), Num(4))) |
|
566 |
eval(Sub(Num(3), Num(2))) |
|
567 |
eval(Sub(Num(3), Num(6))) |
|
568 |
eval(Div(Num(6), Num(2))) |
|
569 |
eval(Div(Num(6), Num(4))) |
|
570 |
||
571 |
def time_needed[T](n: Int, code: => T) = {
|
|
572 |
val start = System.nanoTime() |
|
573 |
for (i <- (0 to n)) code |
|
574 |
val end = System.nanoTime() |
|
575 |
(end - start) / 1.0e9 |
|
576 |
} |
|
577 |
||
578 |
def check(xs: Set[Int], target: Int) = |
|
579 |
search(xs).find(eval(_) == Some(target)) |
|
580 |
||
581 |
for (sol <- check(Set(50, 5, 4, 9, 10, 8), 560)) {
|
|
582 |
println(s"${pp(sol)} => ${eval(sol)}")
|
|
583 |
} |
|
584 |
||
585 |
||
586 |
||
587 |
time_needed(1, check(Set(50, 5, 4, 9, 10, 8), 560)) |
|
588 |
||
589 |
||
590 |
println(check(Set(25, 5, 2, 10, 7, 1), 986).mkString("\n"))
|
|
591 |
||
592 |
for (sol <- check(Set(25, 5, 2, 10, 7, 1), 986)) {
|
|
593 |
println(s"${pp(sol)} => ${eval(sol)}")
|
|
594 |
} |
|
| 478 | 595 |
|
| 506 | 596 |
for (sol <- check(Set(25, 5, 2, 10, 7, 1), -1)) {
|
597 |
println(s"${pp(sol)} => ${eval(sol)}")
|
|
598 |
} |
|
599 |
||
600 |
for (sol <- check(Set(100, 25, 75, 50, 7, 10), 360)) {
|
|
601 |
println(s"${pp(sol)} => ${eval(sol)}")
|
|
602 |
} |
|
603 |
time_needed(1, check(Set(100, 25, 75, 50, 7, 10), 360)) |
|
604 |
||
605 |
||
606 |
||
607 |
time_needed(1, check(Set(25, 5, 2, 10, 7, 1), 986)) |
|
608 |
time_needed(1, check(Set(25, 5, 2, 10, 7, 1), -1)) |
|
609 |
||
610 |
||
611 |
def generate(nums: Set[Int]) : Set[(Tree, Int)] = nums.size match {
|
|
612 |
case 0 => Set() |
|
613 |
case 1 => Set((Num(nums.head), nums.head)) |
|
614 |
case xs => {
|
|
615 |
val spls = splits(nums) |
|
616 |
val subtrs = |
|
617 |
for ((lspls, rspls) <- spls; |
|
618 |
(lt, ln) <- generate(lspls); |
|
619 |
(rt, rn) <- generate(rspls)) yield {
|
|
620 |
Set((Add(lt, rt), ln + rn), |
|
621 |
(Mul(lt, rt), ln * rn)) |
|
622 |
++ Option.when(ln <= rn)((Sub(rt, lt), rn - ln)) |
|
623 |
++ Option.when(ln > rn)((Sub(lt, rt), ln - rn)) |
|
624 |
++ Option.when(rn > 0 && ln % rn == 0)((Div(lt, rt), ln / rn)) |
|
625 |
++ Option.when(ln > 0 && rn % ln == 0)((Div(rt, lt), rn / ln)) |
|
626 |
} |
|
627 |
subtrs.flatten |
|
628 |
} |
|
629 |
} |
|
630 |
||
631 |
def check2(xs: Set[Int], target: Int) = |
|
632 |
generate(xs).find(_._2 == target) |
|
633 |
||
634 |
for ((sol, ev) <- check2(Set(50, 5, 4, 9, 10, 8), 560)) {
|
|
635 |
println(s"${pp(sol)} => ${eval(sol)} / $ev")
|
|
636 |
} |
|
637 |
||
638 |
time_needed(1, check(Set(50, 5, 4, 9, 10, 8), 560)) |
|
639 |
time_needed(1, check2(Set(50, 5, 4, 9, 10, 8), 560)) |
|
640 |
||
641 |
time_needed(1, check(Set(50, 5, 4, 9, 10, 8), -1)) |
|
642 |
time_needed(1, check2(Set(50, 5, 4, 9, 10, 8), -1)) |
|
| 478 | 643 |
|
644 |
||
645 |
// Sudoku |
|
646 |
//======== |
|
647 |
||
648 |
// THE POINT OF THIS CODE IS NOT TO BE SUPER |
|
649 |
// EFFICIENT AND FAST, just explaining exhaustive |
|
650 |
// depth-first search |
|
651 |
||
| 491 | 652 |
//> using dep org.scala-lang.modules::scala-parallel-collections:1.0.4 |
653 |
import scala.collection.parallel.CollectionConverters.* |
|
654 |
||
655 |
||
656 |
val s1 = "s\n" |
|
657 |
val s2 = """s\n""" |
|
| 478 | 658 |
|
659 |
val game0 = """.14.6.3.. |
|
660 |
|62...4..9 |
|
661 |
|.8..5.6.. |
|
662 |
|.6.2....3 |
|
663 |
|.7..1..5. |
|
664 |
|5....9.6. |
|
665 |
|..6.2..3. |
|
666 |
|1..5...92 |
|
667 |
|..7.9.41.""".stripMargin.replaceAll("\\n", "")
|
|
668 |
||
669 |
type Pos = (Int, Int) |
|
670 |
val EmptyValue = '.' |
|
671 |
val MaxValue = 9 |
|
672 |
||
673 |
def pretty(game: String): String = |
|
674 |
"\n" + (game.grouped(MaxValue).mkString("\n"))
|
|
675 |
||
676 |
pretty(game0) |
|
677 |
||
678 |
||
679 |
val allValues = "123456789".toList |
|
680 |
val indexes = (0 to 8).toList |
|
681 |
||
682 |
def empty(game: String) = game.indexOf(EmptyValue) |
|
683 |
def isDone(game: String) = empty(game) == -1 |
|
684 |
def emptyPosition(game: String) : Pos = {
|
|
685 |
val e = empty(game) |
|
686 |
(e % MaxValue, e / MaxValue) |
|
687 |
} |
|
688 |
||
689 |
def get_row(game: String, y: Int) = |
|
690 |
indexes.map(col => game(y * MaxValue + col)) |
|
691 |
def get_col(game: String, x: Int) = |
|
692 |
indexes.map(row => game(x + row * MaxValue)) |
|
693 |
||
694 |
//get_row(game0, 0) |
|
695 |
//get_row(game0, 1) |
|
696 |
//get_col(game0, 0) |
|
697 |
||
698 |
def get_box(game: String, pos: Pos): List[Char] = {
|
|
699 |
def base(p: Int): Int = (p / 3) * 3 |
|
700 |
val x0 = base(pos._1) |
|
701 |
val y0 = base(pos._2) |
|
702 |
val ys = (y0 until y0 + 3).toList |
|
703 |
(x0 until x0 + 3).toList |
|
704 |
.flatMap(x => ys.map(y => game(x + y * MaxValue))) |
|
| 446 | 705 |
} |
706 |
||
707 |
||
| 478 | 708 |
//get_box(game0, (3, 1)) |
709 |
||
710 |
||
711 |
// this is not mutable!! |
|
712 |
def update(game: String, pos: Int, value: Char): String = |
|
713 |
game.updated(pos, value) |
|
714 |
||
715 |
def toAvoid(game: String, pos: Pos): List[Char] = |
|
716 |
(get_col(game, pos._1) ++ |
|
717 |
get_row(game, pos._2) ++ |
|
718 |
get_box(game, pos)) |
|
| 445 | 719 |
|
| 478 | 720 |
def candidates(game: String, pos: Pos): List[Char] = |
721 |
allValues.diff(toAvoid(game, pos)) |
|
722 |
||
723 |
//candidates(game0, (0,0)) |
|
724 |
||
725 |
||
726 |
def search(game: String): List[String] = {
|
|
727 |
if (isDone(game)) List(game) |
|
728 |
else {
|
|
729 |
val cs = candidates(game, emptyPosition(game)) |
|
730 |
cs.par.map(c => search(update(game, empty(game), c))).flatten.toList |
|
731 |
} |
|
| 445 | 732 |
} |
733 |
||
| 478 | 734 |
pretty(game0) |
735 |
search(game0).map(pretty) |
|
| 445 | 736 |
|
| 478 | 737 |
val game1 = """23.915... |
738 |
|...2..54. |
|
739 |
|6.7...... |
|
740 |
|..1.....9 |
|
741 |
|89.5.3.17 |
|
742 |
|5.....6.. |
|
743 |
|......9.5 |
|
744 |
|.16..7... |
|
745 |
|...329..1""".stripMargin.replaceAll("\\n", "")
|
|
746 |
||
747 |
search(game1).map(pretty) |
|
748 |
||
749 |
// a game that is in the hard category |
|
750 |
val game2 = """8........ |
|
751 |
|..36..... |
|
752 |
|.7..9.2.. |
|
753 |
|.5...7... |
|
754 |
|....457.. |
|
755 |
|...1...3. |
|
756 |
|..1....68 |
|
757 |
|..85...1. |
|
758 |
|.9....4..""".stripMargin.replaceAll("\\n", "")
|
|
759 |
||
760 |
search(game2).map(pretty) |
|
761 |
||
762 |
// game with multiple solutions |
|
763 |
val game3 = """.8...9743 |
|
764 |
|.5...8.1. |
|
765 |
|.1....... |
|
766 |
|8....5... |
|
767 |
|...8.4... |
|
768 |
|...3....6 |
|
769 |
|.......7. |
|
770 |
|.3.5...8. |
|
771 |
|9724...5.""".stripMargin.replaceAll("\\n", "")
|
|
772 |
||
773 |
search(game3).map(pretty).foreach(println) |
|
774 |
||
775 |
// for measuring time |
|
776 |
def time_needed[T](i: Int, code: => T) = {
|
|
777 |
val start = System.nanoTime() |
|
778 |
for (j <- 1 to i) code |
|
779 |
val end = System.nanoTime() |
|
780 |
s"${(end - start) / 1.0e9} secs"
|
|
781 |
} |
|
782 |
||
783 |
time_needed(2, search(game2)) |
|
784 |
||
785 |
||
786 |
// concurrency |
|
787 |
// scala-cli --extra-jars scala-parallel-collections_3-1.0.4.jar |
|
788 |
// import scala.collection.parallel.CollectionConverters._ |
|
789 |
||
790 |
||
791 |
||
| 445 | 792 |
|
793 |
// String Interpolations |
|
794 |
//======================= |
|
795 |
||
796 |
def cube(n: Int) : Int = n * n * n |
|
797 |
||
798 |
val n = 3 |
|
799 |
println("The cube of " + n + " is " + cube(n) + ".")
|
|
800 |
||
801 |
println(s"The cube of $n is ${cube(n)}.")
|
|
802 |
||
803 |
// or even |
|
804 |
||
805 |
println(s"The cube of $n is ${n * n * n}.")
|
|
806 |
||
807 |
// helpful for debugging purposes |
|
808 |
// |
|
809 |
// "The most effective debugging tool is still careful |
|
810 |
// thought, coupled with judiciously placed print |
|
811 |
// statements." |
|
812 |
// — Brian W. Kernighan, in Unix for Beginners (1979) |
|
813 |
||
814 |
||
815 |
def gcd_db(a: Int, b: Int) : Int = {
|
|
816 |
println(s"Function called with $a and $b.") |
|
817 |
if (b == 0) a else gcd_db(b, a % b) |
|
818 |
} |
|
819 |
||
820 |
gcd_db(48, 18) |
|
| 320 | 821 |
|
| 415 | 822 |
|
| 343 | 823 |
|
824 |
||
| 320 | 825 |
// Recursion Again ;o) |
826 |
//==================== |
|
827 |
||
| 217 | 828 |
|
| 366 | 829 |
// another well-known example: Towers of Hanoi |
830 |
//============================================= |
|
| 178 | 831 |
|
| 320 | 832 |
def move(from: Char, to: Char) = |
833 |
println(s"Move disc from $from to $to!") |
|
| 67 | 834 |
|
| 320 | 835 |
def hanoi(n: Int, from: Char, via: Char, to: Char) : Unit = {
|
836 |
if (n == 0) () |
|
837 |
else {
|
|
838 |
hanoi(n - 1, from, to, via) |
|
839 |
move(from, to) |
|
840 |
hanoi(n - 1, via, from, to) |
|
841 |
} |
|
842 |
} |
|
| 67 | 843 |
|
| 320 | 844 |
hanoi(4, 'A', 'B', 'C') |
| 67 | 845 |
|
| 155 | 846 |
|
847 |
||
| 320 | 848 |
|
849 |
||
| 478 | 850 |
|
851 |
||
852 |
// Map type (upper-case) |
|
853 |
//======================= |
|
854 |
||
855 |
// Note the difference between map and Map |
|
856 |
||
857 |
val m = Map(1 -> "one", 2 -> "two", 10 -> "many") |
|
858 |
||
859 |
List((1, "one"), (2, "two"), (10, "many")).toMap |
|
860 |
||
861 |
m.get(1) |
|
862 |
m.get(4) |
|
863 |
||
864 |
m.getOrElse(1, "") |
|
865 |
m.getOrElse(4, "") |
|
866 |
||
867 |
val new_m = m + (10 -> "ten") |
|
| 320 | 868 |
|
| 478 | 869 |
new_m.get(10) |
870 |
||
871 |
val m2 = for ((k, v) <- m) yield (k, v.toUpperCase) |
|
872 |
||
873 |
||
874 |
||
875 |
// groupBy function on Maps |
|
876 |
val lst = List("one", "two", "three", "four", "five")
|
|
877 |
lst.groupBy(_.head) |
|
| 320 | 878 |
|
| 478 | 879 |
lst.groupBy(_.length) |
880 |
||
881 |
lst.groupBy(_.length).get(3) |
|
882 |
||
883 |
val grps = lst.groupBy(_.length) |
|
884 |
grps.keySet |
|
885 |
||
886 |
||
887 |
||
| 320 | 888 |
|
889 |
// Tail recursion |
|
890 |
//================ |
|
891 |
||
| 375 | 892 |
def fact(n: BigInt): BigInt = |
| 320 | 893 |
if (n == 0) 1 else n * fact(n - 1) |
894 |
||
895 |
fact(10) //ok |
|
896 |
fact(10000) // produces a stackoverflow |
|
897 |
||
| 375 | 898 |
|
| 320 | 899 |
def factT(n: BigInt, acc: BigInt): BigInt = |
900 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
901 |
||
902 |
factT(10, 1) |
|
903 |
println(factT(100000, 1)) |
|
904 |
||
905 |
// there is a flag for ensuring a function is tail recursive |
|
906 |
import scala.annotation.tailrec |
|
907 |
||
908 |
@tailrec |
|
909 |
def factT(n: BigInt, acc: BigInt): BigInt = |
|
910 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
911 |
||
912 |
||
913 |
||
914 |
// for tail-recursive functions the Scala compiler |
|
915 |
// generates loop-like code, which does not need |
|
916 |
// to allocate stack-space in each recursive |
|
917 |
// call; Scala can do this only for tail-recursive |
|
918 |
// functions |
|
919 |
||
| 375 | 920 |
def length(xs: List[Int]) : Int = xs match {
|
921 |
case Nil => 0 |
|
922 |
case _ :: tail => 1 + length(tail) |
|
923 |
} |
|
| 366 | 924 |
|
| 375 | 925 |
@tailrec |
926 |
def lengthT(xs: List[Int], acc : Int) : Int = xs match {
|
|
927 |
case Nil => acc |
|
928 |
case _ :: tail => lengthT(tail, 1 + acc) |
|
929 |
} |
|
930 |
||
931 |
lengthT(List.fill(10000000)(1), 0) |
|
| 366 | 932 |
|
933 |
||
934 |
||
935 |
||
| 478 | 936 |
|
| 366 | 937 |
|
938 |
||
| 478 | 939 |
// Aside: concurrency |
940 |
// scala-cli --extra-jars scala-parallel-collections_3-1.0.4.jar |
|
| 366 | 941 |
|
| 478 | 942 |
for (n <- (1 to 10)) println(n) |
943 |
||
944 |
import scala.collection.parallel.CollectionConverters._ |
|
945 |
||
946 |
for (n <- (1 to 10).par) println(n) |
|
| 366 | 947 |
|
948 |
||
| 478 | 949 |
// for measuring time |
950 |
def time_needed[T](n: Int, code: => T) = {
|
|
951 |
val start = System.nanoTime() |
|
952 |
for (i <- (0 to n)) code |
|
953 |
val end = System.nanoTime() |
|
954 |
(end - start) / 1.0e9 |
|
| 366 | 955 |
} |
956 |
||
| 478 | 957 |
val list = (1L to 10_000_000L).toList |
958 |
time_needed(10, for (n <- list) yield n + 42) |
|
959 |
time_needed(10, for (n <- list.par) yield n + 42) |
|
| 366 | 960 |
|
| 478 | 961 |
// ...but par does not make everything faster |
| 158 | 962 |
|
| 478 | 963 |
list.sum |
964 |
list.par.sum |
|
| 67 | 965 |
|
| 478 | 966 |
time_needed(10, list.sum) |
967 |
time_needed(10, list.par.sum) |
|
| 158 | 968 |
|
969 |
||
| 478 | 970 |
// Mutable vs Immutable |
971 |
//====================== |
|
972 |
// |
|
973 |
// Remember: |
|
974 |
// - no vars, no ++i, no += |
|
975 |
// - no mutable data-structures (no Arrays, no ListBuffers) |
|
| 158 | 976 |
|
| 478 | 977 |
// But what the heck....lets try to count to 1 Mio in parallel |
978 |
// |
|
979 |
// requires |
|
980 |
// scala-cli --extra-jars scala- parallel-collections_3-1.0.4.jar |
|
981 |
||
982 |
import scala.collection.parallel.CollectionConverters._ |
|
983 |
||
984 |
def test() = {
|
|
985 |
var cnt = 0 |
|
986 |
||
987 |
for(i <- (1 to 100_000).par) cnt += 1 |
|
988 |
||
989 |
println(s"Should be 100000: $cnt") |
|
| 67 | 990 |
} |
991 |
||
| 478 | 992 |
test() |
993 |
||
994 |
// Or |
|
995 |
// Q: Count how many elements are in the intersections of |
|
996 |
// two sets? |
|
997 |
// A; IMPROPER WAY (mutable counter) |
|
998 |
||
999 |
def count_intersection(A: Set[Int], B: Set[Int]) : Int = {
|
|
1000 |
var count = 0 |
|
1001 |
for (x <- A.par; if B contains x) count += 1 |
|
1002 |
count |
|
1003 |
} |
|
1004 |
||
1005 |
val A = (0 to 999).toSet |
|
1006 |
val B = (0 to 999 by 4).toSet |
|
1007 |
||
1008 |
count_intersection(A, B) |
|
1009 |
||
1010 |
// but do not try to add .par to the for-loop above |
|
| 217 | 1011 |
|
| 158 | 1012 |
|
| 478 | 1013 |
//propper parallel version |
1014 |
def count_intersection2(A: Set[Int], B: Set[Int]) : Int = |
|
1015 |
A.par.count(x => B contains x) |
|
| 155 | 1016 |
|
| 478 | 1017 |
count_intersection2(A, B) |
| 67 | 1018 |
|
|
77
3cbe3d90b77f
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
73
diff
changeset
|
1019 |