author | Christian Urban <christian.urban@kcl.ac.uk> |
Fri, 12 Sep 2025 10:36:07 +0100 | |
changeset 495 | b47879225270 |
parent 494 | 253d1ccb65de |
permissions | -rw-r--r-- |
222 | 1 |
// Scala Lecture 4 |
2 |
//================= |
|
3 |
||
494 | 4 |
//=================== |
5 |
// polymorphic types |
|
6 |
// (algebraic) datatypes and pattern-matching |
|
7 |
// extensions and implicits |
|
418 | 8 |
// tail-recursion |
494 | 9 |
|
10 |
||
11 |
||
12 |
// You do not want to write functions like contains, first, |
|
13 |
// length and so on for every type of lists. |
|
14 |
||
15 |
def length_int_list(lst: List[Int]): Int = lst match { |
|
16 |
case Nil => 0 |
|
17 |
case _::xs => 1 + length_int_list(xs) |
|
18 |
} |
|
19 |
||
20 |
length_int_list(List(1, 2, 3, 4)) |
|
21 |
||
22 |
def length_string_list(lst: List[String]): Int = lst match { |
|
23 |
case Nil => 0 |
|
24 |
case _::xs => 1 + length_string_list(xs) |
|
25 |
} |
|
26 |
||
27 |
length_string_list(List("1", "2", "3", "4")) |
|
28 |
||
29 |
||
30 |
// you can make the function parametric in type(s) |
|
31 |
||
32 |
def length[A](lst: List[A]): Int = lst match { |
|
33 |
case Nil => 0 |
|
34 |
case x::xs => 1 + length(xs) |
|
35 |
} |
|
36 |
length(List("1", "2", "3", "4")) |
|
37 |
length(List(1, 2, 3, 4)) |
|
38 |
||
39 |
||
40 |
length[String](List(1, 2, 3, 4)) |
|
41 |
||
42 |
||
43 |
def map[A, B](lst: List[A], f: A => B): List[B] = lst match { |
|
44 |
case Nil => Nil |
|
45 |
case x::xs => f(x)::map(xs, f) |
|
46 |
} |
|
47 |
||
48 |
map(List(1, 2, 3, 4), (x: Int) => x.toString) |
|
49 |
||
50 |
||
51 |
// Type inference is local in Scala |
|
52 |
||
53 |
def id[T](x: T) : T = x |
|
54 |
||
55 |
val x = id(322) // Int |
|
56 |
val y = id("hey") // String |
|
57 |
val z = id(Set(1,2,3,4)) // Set[Int] |
|
58 |
||
59 |
||
60 |
// The type variable concept in Scala can get |
|
61 |
// really complicated. |
|
62 |
// |
|
63 |
// - variance (OO) |
|
64 |
// - bounds (subtyping) |
|
65 |
// - quantification |
|
66 |
||
67 |
// Java has issues with this too: Java allows |
|
68 |
// to write the following incorrect code, and |
|
69 |
// only recovers by raising an exception |
|
70 |
// at runtime. |
|
71 |
||
72 |
// Object[] arr = new Integer[10]; |
|
73 |
// arr[0] = "Hello World"; |
|
74 |
||
75 |
||
76 |
// Scala gives you a compile-time error, which |
|
77 |
// is much better. |
|
78 |
||
79 |
var arr = Array[Int]() |
|
80 |
arr(0) = "Hello World" |
|
81 |
||
481 | 82 |
|
83 |
||
84 |
||
85 |
// Pattern Matching |
|
86 |
//================== |
|
87 |
||
88 |
// A powerful tool which has even landed in Java during |
|
89 |
// the last few years (https://inside.java/2021/06/13/podcast-017/). |
|
90 |
// ...Scala already has it for many years and the concept is |
|
91 |
// older than your friendly lecturer, that is stone old ;o) |
|
418 | 92 |
|
481 | 93 |
// The general schema: |
94 |
// |
|
95 |
// expression match { |
|
96 |
// case pattern1 => expression1 |
|
97 |
// case pattern2 => expression2 |
|
98 |
// ... |
|
99 |
// case patternN => expressionN |
|
100 |
// } |
|
101 |
||
102 |
||
103 |
// recall |
|
104 |
def len(xs: List[Int]) : Int = { |
|
105 |
if (xs == Nil) 0 |
|
106 |
else 1 + len(xs.tail) |
|
107 |
} |
|
418 | 108 |
|
481 | 109 |
def len(xs: List[Int]) : Int = xs match { |
110 |
case Nil => 0 |
|
111 |
case _::xs => 1 + len(xs) |
|
112 |
} |
|
113 |
||
114 |
len(Nil) |
|
115 |
len(List(1,2,3,4)) |
|
116 |
||
117 |
||
494 | 118 |
//================= |
119 |
// Trees (example of an Algebraic Datatype) |
|
481 | 120 |
|
494 | 121 |
abstract class Tree |
122 |
case class Leaf(x: Int) extends Tree |
|
123 |
case class Node(s: String, left: Tree, right: Tree) extends Tree |
|
481 | 124 |
|
494 | 125 |
val lf = Leaf(20) |
126 |
val tr = Node("foo", Leaf(10), Leaf(23)) |
|
481 | 127 |
|
494 | 128 |
val lst : List[Tree] = List(lf, tr) |
481 | 129 |
|
130 |
||
131 |
||
418 | 132 |
|
481 | 133 |
abstract class Rexp |
134 |
case object ZERO extends Rexp // matches nothing |
|
135 |
case object ONE extends Rexp // matches the empty string |
|
136 |
case class CHAR(c: Char) extends Rexp // matches a character c |
|
137 |
case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative |
|
138 |
case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence |
|
139 |
case class STAR(r: Rexp) extends Rexp // star |
|
418 | 140 |
|
481 | 141 |
def depth(r: Rexp) : Int = r match { |
142 |
case ZERO => 1 |
|
143 |
case ONE => 1 |
|
144 |
case CHAR(_) => 1 |
|
145 |
case ALT(r1, r2) => 1 + List(depth(r1), depth(r2)).max |
|
146 |
case SEQ(r1, r2) => 1 + List(depth(r1), depth(r2)).max |
|
147 |
case STAR(r1) => 1 + depth(r1) |
|
148 |
} |
|
149 |
||
150 |
||
151 |
||
152 |
||
418 | 153 |
|
222 | 154 |
|
325 | 155 |
// expressions (essentially trees) |
156 |
||
481 | 157 |
sealed abstract class Exp |
325 | 158 |
case class N(n: Int) extends Exp // for numbers |
159 |
case class Plus(e1: Exp, e2: Exp) extends Exp |
|
160 |
case class Times(e1: Exp, e2: Exp) extends Exp |
|
161 |
||
162 |
def string(e: Exp) : String = e match { |
|
163 |
case N(n) => s"$n" |
|
164 |
case Plus(e1, e2) => s"(${string(e1)} + ${string(e2)})" |
|
165 |
case Times(e1, e2) => s"(${string(e1)} * ${string(e2)})" |
|
166 |
} |
|
167 |
||
168 |
val e = Plus(N(9), Times(N(3), N(4))) |
|
481 | 169 |
println(e.toString) |
325 | 170 |
println(string(e)) |
171 |
||
172 |
def eval(e: Exp) : Int = e match { |
|
173 |
case N(n) => n |
|
174 |
case Plus(e1, e2) => eval(e1) + eval(e2) |
|
175 |
case Times(e1, e2) => eval(e1) * eval(e2) |
|
176 |
} |
|
177 |
||
178 |
println(eval(e)) |
|
179 |
||
180 |
// simplification rules: |
|
181 |
// e + 0, 0 + e => e |
|
182 |
// e * 0, 0 * e => 0 |
|
183 |
// e * 1, 1 * e => e |
|
326 | 184 |
// |
481 | 185 |
// (....9 ....) |
325 | 186 |
|
187 |
def simp(e: Exp) : Exp = e match { |
|
188 |
case N(n) => N(n) |
|
189 |
case Plus(e1, e2) => (simp(e1), simp(e2)) match { |
|
190 |
case (N(0), e2s) => e2s |
|
191 |
case (e1s, N(0)) => e1s |
|
192 |
case (e1s, e2s) => Plus(e1s, e2s) |
|
193 |
} |
|
194 |
case Times(e1, e2) => (simp(e1), simp(e2)) match { |
|
195 |
case (N(0), _) => N(0) |
|
196 |
case (_, N(0)) => N(0) |
|
197 |
case (N(1), e2s) => e2s |
|
198 |
case (e1s, N(1)) => e1s |
|
199 |
case (e1s, e2s) => Times(e1s, e2s) |
|
200 |
} |
|
201 |
} |
|
202 |
||
203 |
||
204 |
val e2 = Times(Plus(N(0), N(1)), Plus(N(0), N(9))) |
|
205 |
println(string(e2)) |
|
206 |
println(string(simp(e2))) |
|
207 |
||
208 |
||
481 | 209 |
|
210 |
||
211 |
||
212 |
||
213 |
||
325 | 214 |
// Tokens and Reverse Polish Notation |
215 |
abstract class Token |
|
216 |
case class T(n: Int) extends Token |
|
217 |
case object PL extends Token |
|
218 |
case object TI extends Token |
|
219 |
||
220 |
// transfroming an Exp into a list of tokens |
|
221 |
def rp(e: Exp) : List[Token] = e match { |
|
222 |
case N(n) => List(T(n)) |
|
223 |
case Plus(e1, e2) => rp(e1) ::: rp(e2) ::: List(PL) |
|
224 |
case Times(e1, e2) => rp(e1) ::: rp(e2) ::: List(TI) |
|
225 |
} |
|
226 |
println(string(e2)) |
|
227 |
println(rp(e2)) |
|
228 |
||
326 | 229 |
def comp(ls: List[Token], st: List[Int] = Nil) : Int = (ls, st) match { |
325 | 230 |
case (Nil, st) => st.head |
231 |
case (T(n)::rest, st) => comp(rest, n::st) |
|
232 |
case (PL::rest, n1::n2::st) => comp(rest, n1 + n2::st) |
|
233 |
case (TI::rest, n1::n2::st) => comp(rest, n1 * n2::st) |
|
234 |
} |
|
235 |
||
326 | 236 |
comp(rp(e)) |
325 | 237 |
|
238 |
def proc(s: String) : Token = s match { |
|
239 |
case "+" => PL |
|
240 |
case "*" => TI |
|
241 |
case _ => T(s.toInt) |
|
242 |
} |
|
243 |
||
244 |
comp("1 2 + 4 * 5 + 3 +".split(" ").toList.map(proc), Nil) |
|
245 |
||
246 |
||
481 | 247 |
// Tail recursion |
248 |
//================ |
|
249 |
||
250 |
def fact(n: BigInt): BigInt = |
|
251 |
if (n == 0) 1 else n * fact(n - 1) |
|
252 |
||
253 |
||
254 |
fact(10) |
|
255 |
fact(1000) |
|
256 |
fact(100000) |
|
257 |
||
258 |
||
259 |
def factT(n: BigInt, acc: BigInt): BigInt = |
|
260 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
261 |
||
262 |
||
494 | 263 |
factT(1000,1) |
481 | 264 |
println(factT(100000, 1)) |
265 |
||
266 |
||
267 |
// there is a flag for ensuring a function is tail recursive |
|
268 |
import scala.annotation.tailrec |
|
269 |
||
270 |
@tailrec |
|
271 |
def factT(n: BigInt, acc: BigInt): BigInt = |
|
272 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
273 |
||
274 |
factT(100000, 1) |
|
275 |
||
276 |
// for tail-recursive functions the Scala compiler |
|
277 |
// generates loop-like code, which does not need |
|
278 |
// to allocate stack-space in each recursive |
|
279 |
// call; Scala can do this only for tail-recursive |
|
280 |
// functions |
|
281 |
||
282 |
// Moral: Whenever a recursive function is resource-critical |
|
283 |
// (i.e. works with a large recursion depth), then you need to |
|
284 |
// write it in tail-recursive fashion. |
|
285 |
// |
|
286 |
// Unfortuantely, Scala because of current limitations in |
|
287 |
// the JVM is not as clever as other functional languages. It can |
|
288 |
// only optimise "self-tail calls". This excludes the cases of |
|
289 |
// multiple functions making tail calls to each other. Well, |
|
290 |
// nothing is perfect. |
|
291 |
||
292 |
||
494 | 293 |
// default arguments |
380 | 294 |
|
494 | 295 |
def factT(n: BigInt, acc: BigInt = 1): BigInt = |
296 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
380 | 297 |
|
494 | 298 |
factT(1_000_000) |
380 | 299 |
|
300 |
||
494 | 301 |
def length[A](xs: List[A]) : Int = xs match { |
302 |
case Nil => 0 |
|
303 |
case _ :: tail => 1 + length(tail) |
|
380 | 304 |
} |
305 |
||
494 | 306 |
length(List.fill(100000)(1)) |
380 | 307 |
|
494 | 308 |
def lengthT[A](xs: List[A], acc : Int = 0) : Int = xs match { |
309 |
case Nil => acc |
|
310 |
case _ :: tail => lengthT(tail, 1 + acc) |
|
311 |
} |
|
380 | 312 |
|
494 | 313 |
lengthT(List.fill(100000)(1)) |
380 | 314 |
|
315 |
||
316 |
||
317 |
||
318 |
||
319 |
||
320 |
||
321 |
||
322 |
// Function definitions again |
|
323 |
//============================ |
|
324 |
||
325 |
// variable arguments |
|
326 |
||
327 |
def printAll(strings: String*) = { |
|
328 |
strings.foreach(println) |
|
329 |
} |
|
330 |
||
331 |
printAll() |
|
332 |
printAll("foo") |
|
333 |
printAll("foo", "bar") |
|
334 |
printAll("foo", "bar", "baz") |
|
335 |
||
336 |
// pass a list to the varargs field |
|
337 |
val fruits = List("apple", "banana", "cherry") |
|
338 |
||
339 |
printAll(fruits: _*) |
|
340 |
||
341 |
||
342 |
// you can also implement your own string interpolations |
|
343 |
import scala.language.implicitConversions |
|
344 |
import scala.language.reflectiveCalls |
|
345 |
||
346 |
implicit def sring_inters(sc: StringContext) = new { |
|
347 |
def i(args: Any*): String = s"${sc.s(args:_*)}\n" |
|
348 |
} |
|
349 |
||
350 |
i"add ${3+2} ${3 * 3}" |
|
351 |
||
352 |
||
353 |
||
354 |
||
355 |
// currying (Haskell Curry) |
|
356 |
||
357 |
def add(x: Int, y: Int) = x + y |
|
358 |
||
359 |
List(1,2,3,4,5).map(x => add(3, x)) |
|
360 |
||
361 |
def add2(x: Int)(y: Int) = x + y |
|
362 |
||
363 |
List(1,2,3,4,5).map(add2(3)) |
|
364 |
||
365 |
val a3 : Int => Int = add2(3) |
|
366 |
||
367 |
// currying helps sometimes with type inference |
|
368 |
||
369 |
def find[A](xs: List[A])(pred: A => Boolean): Option[A] = { |
|
370 |
xs match { |
|
371 |
case Nil => None |
|
372 |
case hd :: tl => |
|
373 |
if (pred(hd)) Some(hd) else find(tl)(pred) |
|
374 |
} |
|
375 |
} |
|
376 |
||
377 |
find(List(1, 2, 3))(x => x % 2 == 0) |
|
378 |
||
379 |
// Source.fromURL(url)(encoding) |
|
380 |
// Source.fromFile(name)(encoding) |
|
325 | 381 |
|
382 |
||
384 | 383 |
|
382 | 384 |
|
385 |
||
386 |
||
387 |
||
325 | 388 |
// Sudoku |
389 |
//======== |
|
390 |
||
391 |
// THE POINT OF THIS CODE IS NOT TO BE SUPER |
|
392 |
// EFFICIENT AND FAST, just explaining exhaustive |
|
393 |
// depth-first search |
|
394 |
||
395 |
||
396 |
val game0 = """.14.6.3.. |
|
397 |
|62...4..9 |
|
398 |
|.8..5.6.. |
|
399 |
|.6.2....3 |
|
400 |
|.7..1..5. |
|
401 |
|5....9.6. |
|
402 |
|..6.2..3. |
|
403 |
|1..5...92 |
|
404 |
|..7.9.41.""".stripMargin.replaceAll("\\n", "") |
|
405 |
||
383 | 406 |
|
326 | 407 |
|
325 | 408 |
type Pos = (Int, Int) |
409 |
val EmptyValue = '.' |
|
410 |
val MaxValue = 9 |
|
411 |
||
383 | 412 |
def pretty(game: String): String = |
413 |
"\n" + (game.grouped(MaxValue).mkString("\n")) |
|
414 |
||
415 |
pretty(game0) |
|
416 |
||
417 |
||
325 | 418 |
val allValues = "123456789".toList |
419 |
val indexes = (0 to 8).toList |
|
420 |
||
421 |
def empty(game: String) = game.indexOf(EmptyValue) |
|
422 |
def isDone(game: String) = empty(game) == -1 |
|
383 | 423 |
def emptyPosition(game: String) = { |
424 |
val e = empty(game) |
|
425 |
(e % MaxValue, e / MaxValue) |
|
426 |
} |
|
325 | 427 |
|
428 |
def get_row(game: String, y: Int) = |
|
429 |
indexes.map(col => game(y * MaxValue + col)) |
|
430 |
def get_col(game: String, x: Int) = |
|
431 |
indexes.map(row => game(x + row * MaxValue)) |
|
432 |
||
383 | 433 |
//get_row(game0, 0) |
434 |
//get_row(game0, 1) |
|
435 |
//get_col(game0, 0) |
|
326 | 436 |
|
325 | 437 |
def get_box(game: String, pos: Pos): List[Char] = { |
438 |
def base(p: Int): Int = (p / 3) * 3 |
|
439 |
val x0 = base(pos._1) |
|
440 |
val y0 = base(pos._2) |
|
441 |
val ys = (y0 until y0 + 3).toList |
|
383 | 442 |
(x0 until x0 + 3).toList |
443 |
.flatMap(x => ys.map(y => game(x + y * MaxValue))) |
|
325 | 444 |
} |
445 |
||
383 | 446 |
|
325 | 447 |
//get_box(game0, (3, 1)) |
448 |
||
449 |
||
450 |
// this is not mutable!! |
|
451 |
def update(game: String, pos: Int, value: Char): String = |
|
452 |
game.updated(pos, value) |
|
453 |
||
454 |
def toAvoid(game: String, pos: Pos): List[Char] = |
|
383 | 455 |
(get_col(game, pos._1) ++ |
456 |
get_row(game, pos._2) ++ |
|
457 |
get_box(game, pos)) |
|
325 | 458 |
|
459 |
def candidates(game: String, pos: Pos): List[Char] = |
|
460 |
allValues.diff(toAvoid(game, pos)) |
|
461 |
||
462 |
//candidates(game0, (0,0)) |
|
463 |
||
464 |
||
465 |
def search(game: String): List[String] = { |
|
466 |
if (isDone(game)) List(game) |
|
467 |
else { |
|
468 |
val cs = candidates(game, emptyPosition(game)) |
|
383 | 469 |
cs.map(c => search(update(game, empty(game), c))).flatten |
325 | 470 |
} |
471 |
} |
|
472 |
||
383 | 473 |
pretty(game0) |
325 | 474 |
search(game0).map(pretty) |
475 |
||
476 |
val game1 = """23.915... |
|
477 |
|...2..54. |
|
478 |
|6.7...... |
|
479 |
|..1.....9 |
|
480 |
|89.5.3.17 |
|
481 |
|5.....6.. |
|
482 |
|......9.5 |
|
483 |
|.16..7... |
|
484 |
|...329..1""".stripMargin.replaceAll("\\n", "") |
|
485 |
||
486 |
search(game1).map(pretty) |
|
487 |
||
488 |
// a game that is in the hard category |
|
489 |
val game2 = """8........ |
|
490 |
|..36..... |
|
491 |
|.7..9.2.. |
|
492 |
|.5...7... |
|
493 |
|....457.. |
|
494 |
|...1...3. |
|
495 |
|..1....68 |
|
496 |
|..85...1. |
|
497 |
|.9....4..""".stripMargin.replaceAll("\\n", "") |
|
498 |
||
499 |
search(game2).map(pretty) |
|
500 |
||
501 |
// game with multiple solutions |
|
502 |
val game3 = """.8...9743 |
|
503 |
|.5...8.1. |
|
504 |
|.1....... |
|
505 |
|8....5... |
|
506 |
|...8.4... |
|
507 |
|...3....6 |
|
508 |
|.......7. |
|
509 |
|.3.5...8. |
|
510 |
|9724...5.""".stripMargin.replaceAll("\\n", "") |
|
511 |
||
512 |
search(game3).map(pretty).foreach(println) |
|
513 |
||
514 |
// for measuring time |
|
515 |
def time_needed[T](i: Int, code: => T) = { |
|
516 |
val start = System.nanoTime() |
|
517 |
for (j <- 1 to i) code |
|
518 |
val end = System.nanoTime() |
|
519 |
s"${(end - start) / 1.0e9} secs" |
|
520 |
} |
|
521 |
||
522 |
time_needed(1, search(game2)) |
|
523 |
||
524 |
||
525 |
||
384 | 526 |
// tail recursive version that searches |
527 |
// for all Sudoku solutions |
|
325 | 528 |
import scala.annotation.tailrec |
529 |
||
530 |
@tailrec |
|
384 | 531 |
def searchT(games: List[String], sols: List[String]): List[String] = |
532 |
games match { |
|
533 |
case Nil => sols |
|
534 |
case game::rest => { |
|
535 |
if (isDone(game)) searchT(rest, game::sols) |
|
536 |
else { |
|
537 |
val cs = candidates(game, emptyPosition(game)) |
|
494 | 538 |
searchT(cs.map(c => update(game, empty(game), c)) |
539 |
::: rest, sols) |
|
384 | 540 |
} |
541 |
} |
|
542 |
} |
|
325 | 543 |
|
544 |
searchT(List(game3), List()).map(pretty) |
|
545 |
||
546 |
||
547 |
// tail recursive version that searches |
|
548 |
// for a single solution |
|
549 |
||
550 |
def search1T(games: List[String]): Option[String] = games match { |
|
551 |
case Nil => None |
|
552 |
case game::rest => { |
|
553 |
if (isDone(game)) Some(game) |
|
554 |
else { |
|
555 |
val cs = candidates(game, emptyPosition(game)) |
|
556 |
search1T(cs.map(c => update(game, empty(game), c)) ::: rest) |
|
557 |
} |
|
558 |
} |
|
559 |
} |
|
560 |
||
561 |
search1T(List(game3)).map(pretty) |
|
562 |
time_needed(1, search1T(List(game3))) |
|
563 |
time_needed(1, search1T(List(game2))) |
|
564 |
||
565 |
// game with multiple solutions |
|
566 |
val game3 = """.8...9743 |
|
567 |
|.5...8.1. |
|
568 |
|.1....... |
|
569 |
|8....5... |
|
570 |
|...8.4... |
|
571 |
|...3....6 |
|
572 |
|.......7. |
|
573 |
|.3.5...8. |
|
574 |
|9724...5.""".stripMargin.replaceAll("\\n", "") |
|
575 |
||
576 |
searchT(List(game3), Nil).map(pretty) |
|
577 |
search1T(List(game3)).map(pretty) |
|
578 |
||
579 |
||
580 |
||
222 | 581 |
|
582 |
||
583 |
||
325 | 584 |
// Cool Stuff in Scala |
585 |
//===================== |
|
586 |
||
587 |
||
588 |
// Implicits or How to Pimp your Library |
|
589 |
//====================================== |
|
590 |
// |
|
591 |
// For example adding your own methods to Strings: |
|
592 |
// Imagine you want to increment strings, like |
|
593 |
// |
|
594 |
// "HAL".increment |
|
595 |
// |
|
596 |
// you can avoid ugly fudges, like a MyString, by |
|
494 | 597 |
// using an extension. |
325 | 598 |
|
599 |
||
494 | 600 |
extension (s: String) { |
325 | 601 |
def increment = s.map(c => (c + 1).toChar) |
602 |
} |
|
603 |
||
455 | 604 |
"HAL".increment |
325 | 605 |
|
606 |
||
607 |
||
381
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
608 |
|
325 | 609 |
|
610 |
import scala.concurrent.duration.{TimeUnit,SECONDS,MINUTES} |
|
611 |
||
612 |
case class Duration(time: Long, unit: TimeUnit) { |
|
613 |
def +(o: Duration) = |
|
614 |
Duration(time + unit.convert(o.time, o.unit), unit) |
|
615 |
} |
|
616 |
||
494 | 617 |
extension (that: Int) { |
381
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
618 |
def seconds = Duration(that, SECONDS) |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
619 |
def minutes = Duration(that, MINUTES) |
325 | 620 |
} |
621 |
||
622 |
5.seconds + 2.minutes //Duration(125L, SECONDS ) |
|
623 |
2.minutes + 60.seconds |
|
624 |
||
625 |
||
626 |
||
627 |
||
628 |
// Regular expressions - the power of DSLs in Scala |
|
629 |
//================================================== |
|
630 |
||
631 |
abstract class Rexp |
|
632 |
case object ZERO extends Rexp // nothing |
|
633 |
case object ONE extends Rexp // the empty string |
|
634 |
case class CHAR(c: Char) extends Rexp // a character c |
|
635 |
case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative r1 + r2 |
|
636 |
case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence r1 . r2 |
|
637 |
case class STAR(r: Rexp) extends Rexp // star r* |
|
638 |
||
639 |
||
640 |
||
641 |
// writing (ab)* in the format above is |
|
642 |
// tedious |
|
643 |
val r0 = STAR(SEQ(CHAR('a'), CHAR('b'))) |
|
644 |
||
645 |
||
646 |
// some convenience for typing in regular expressions |
|
647 |
import scala.language.implicitConversions |
|
648 |
||
649 |
def charlist2rexp(s: List[Char]): Rexp = s match { |
|
650 |
case Nil => ONE |
|
651 |
case c::Nil => CHAR(c) |
|
652 |
case c::s => SEQ(CHAR(c), charlist2rexp(s)) |
|
653 |
} |
|
326 | 654 |
|
494 | 655 |
given Conversion[String, Rexp] = |
656 |
(s => charlist2rexp(s.toList)) |
|
325 | 657 |
|
418 | 658 |
val r1 = STAR("ab") |
381
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
659 |
val r2 = STAR("hello") | STAR("world") |
325 | 660 |
|
661 |
||
494 | 662 |
extension (r: Rexp) { |
325 | 663 |
def | (s: Rexp) = ALT(r, s) |
664 |
def % = STAR(r) |
|
665 |
def ~ (s: Rexp) = SEQ(r, s) |
|
666 |
} |
|
667 |
||
494 | 668 |
//example regular expressions |
325 | 669 |
|
494 | 670 |
val rex = "ab".% |
381
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
671 |
|
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
672 |
|
326 | 673 |
val digit = ("0" | "1" | "2" | "3" | "4" | |
674 |
"5" | "6" | "7" | "8" | "9") |
|
325 | 675 |
val sign = "+" | "-" | "" |
676 |
val number = sign ~ digit ~ digit.% |
|
677 |
||
678 |
||
679 |
||
381
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
680 |
|
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
681 |
// In mandelbrot.scala I used complex (imaginary) numbers |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
682 |
// and implemented the usual arithmetic operations for complex |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
683 |
// numbers. |
325 | 684 |
|
381
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
685 |
case class Complex(re: Double, im: Double) { |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
686 |
// represents the complex number re + im * i |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
687 |
def +(that: Complex) = Complex(this.re + that.re, this.im + that.im) |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
688 |
def -(that: Complex) = Complex(this.re - that.re, this.im - that.im) |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
689 |
def *(that: Complex) = Complex(this.re * that.re - this.im * that.im, |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
690 |
this.re * that.im + that.re * this.im) |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
691 |
def *(that: Double) = Complex(this.re * that, this.im * that) |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
692 |
def abs = Math.sqrt(this.re * this.re + this.im * this.im) |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
693 |
} |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
694 |
|
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
695 |
val test = Complex(1, 2) + Complex (3, 4) |
222 | 696 |
|
325 | 697 |
|
381
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
698 |
// ...to allow the notation n + m * i |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
699 |
import scala.language.implicitConversions |
325 | 700 |
|
381
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
701 |
val i = Complex(0, 1) |
494 | 702 |
given Conversion[Double, Complex] = (re: Double) => Complex(re, 0) |
222 | 703 |
|
381
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
704 |
val inum1 = -2.0 + -1.5 * i |
116fa3c8584f
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
705 |
val inum2 = 1.0 + 1.5 * i |