| author | Christian Urban <christian.urban@kcl.ac.uk> |
| Thu, 11 Dec 2025 13:23:30 +0000 | |
| changeset 507 | 2e3945ff7b66 |
| parent 491 | 2a30c7dfe3ed |
| permissions | -rw-r--r-- |
| 222 | 1 |
// Scala Lecture 4 |
2 |
//================= |
|
3 |
||
| 491 | 4 |
//=================== |
5 |
// polymorphic types |
|
6 |
// (algebraic) datatypes and pattern-matching |
|
7 |
// extensions and implicits |
|
| 415 | 8 |
// tail-recursion |
| 491 | 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 |
||
| 507 | 40 |
length[Int](List(1, 2, 3, 4)) |
| 491 | 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 |
||
| 478 | 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) |
|
| 415 | 92 |
|
| 478 | 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 |
} |
|
| 415 | 108 |
|
| 478 | 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 |
||
| 491 | 118 |
//================= |
119 |
// Trees (example of an Algebraic Datatype) |
|
| 478 | 120 |
|
| 491 | 121 |
abstract class Tree |
122 |
case class Leaf(x: Int) extends Tree |
|
123 |
case class Node(s: String, left: Tree, right: Tree) extends Tree |
|
| 478 | 124 |
|
| 491 | 125 |
val lf = Leaf(20) |
126 |
val tr = Node("foo", Leaf(10), Leaf(23))
|
|
| 478 | 127 |
|
| 491 | 128 |
val lst : List[Tree] = List(lf, tr) |
| 478 | 129 |
|
130 |
||
131 |
||
| 415 | 132 |
|
| 478 | 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 |
|
| 415 | 140 |
|
| 478 | 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 |
||
| 415 | 153 |
|
| 222 | 154 |
|
| 325 | 155 |
// expressions (essentially trees) |
156 |
||
| 478 | 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))) |
|
| 478 | 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 |
// |
| 478 | 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 |
||
| 478 | 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 |
||
| 478 | 247 |
// Tail recursion |
248 |
//================ |
|
249 |
||
| 507 | 250 |
@tailrec |
| 478 | 251 |
def fact(n: BigInt): BigInt = |
252 |
if (n == 0) 1 else n * fact(n - 1) |
|
253 |
||
| 507 | 254 |
fact(3) -> fact(2) |
255 |
||
256 |
||
| 478 | 257 |
|
258 |
fact(10) |
|
259 |
fact(1000) |
|
260 |
fact(100000) |
|
261 |
||
262 |
||
263 |
def factT(n: BigInt, acc: BigInt): BigInt = |
|
264 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
265 |
||
266 |
||
| 507 | 267 |
factT(10,1) |
| 478 | 268 |
println(factT(100000, 1)) |
269 |
||
270 |
||
271 |
// there is a flag for ensuring a function is tail recursive |
|
272 |
import scala.annotation.tailrec |
|
273 |
||
274 |
@tailrec |
|
275 |
def factT(n: BigInt, acc: BigInt): BigInt = |
|
276 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
277 |
||
278 |
factT(100000, 1) |
|
279 |
||
280 |
// for tail-recursive functions the Scala compiler |
|
281 |
// generates loop-like code, which does not need |
|
282 |
// to allocate stack-space in each recursive |
|
283 |
// call; Scala can do this only for tail-recursive |
|
284 |
// functions |
|
285 |
||
286 |
// Moral: Whenever a recursive function is resource-critical |
|
287 |
// (i.e. works with a large recursion depth), then you need to |
|
288 |
// write it in tail-recursive fashion. |
|
289 |
// |
|
290 |
// Unfortuantely, Scala because of current limitations in |
|
291 |
// the JVM is not as clever as other functional languages. It can |
|
292 |
// only optimise "self-tail calls". This excludes the cases of |
|
293 |
// multiple functions making tail calls to each other. Well, |
|
294 |
// nothing is perfect. |
|
295 |
||
296 |
||
| 491 | 297 |
// default arguments |
| 380 | 298 |
|
| 491 | 299 |
def factT(n: BigInt, acc: BigInt = 1): BigInt = |
300 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
| 380 | 301 |
|
| 491 | 302 |
factT(1_000_000) |
| 380 | 303 |
|
304 |
||
| 491 | 305 |
def length[A](xs: List[A]) : Int = xs match {
|
306 |
case Nil => 0 |
|
307 |
case _ :: tail => 1 + length(tail) |
|
| 380 | 308 |
} |
309 |
||
| 507 | 310 |
val long_lst = List.fill(100000)(1) |
311 |
||
312 |
length(long_lst) |
|
313 |
long_lst.length |
|
| 380 | 314 |
|
| 491 | 315 |
def lengthT[A](xs: List[A], acc : Int = 0) : Int = xs match {
|
316 |
case Nil => acc |
|
317 |
case _ :: tail => lengthT(tail, 1 + acc) |
|
318 |
} |
|
| 380 | 319 |
|
| 507 | 320 |
|
| 380 | 321 |
|
322 |
||
323 |
||
324 |
||
325 |
||
326 |
||
327 |
||
328 |
||
329 |
// Function definitions again |
|
330 |
//============================ |
|
331 |
||
332 |
// variable arguments |
|
333 |
||
334 |
def printAll(strings: String*) = {
|
|
335 |
strings.foreach(println) |
|
336 |
} |
|
337 |
||
338 |
printAll() |
|
339 |
printAll("foo")
|
|
340 |
printAll("foo", "bar")
|
|
341 |
printAll("foo", "bar", "baz")
|
|
342 |
||
343 |
// pass a list to the varargs field |
|
344 |
val fruits = List("apple", "banana", "cherry")
|
|
345 |
||
346 |
printAll(fruits: _*) |
|
347 |
||
348 |
||
349 |
// you can also implement your own string interpolations |
|
350 |
import scala.language.implicitConversions |
|
351 |
import scala.language.reflectiveCalls |
|
352 |
||
353 |
implicit def sring_inters(sc: StringContext) = new {
|
|
354 |
def i(args: Any*): String = s"${sc.s(args:_*)}\n"
|
|
355 |
} |
|
356 |
||
357 |
i"add ${3+2} ${3 * 3}"
|
|
358 |
||
359 |
||
360 |
||
361 |
||
362 |
// currying (Haskell Curry) |
|
363 |
||
364 |
def add(x: Int, y: Int) = x + y |
|
365 |
||
366 |
List(1,2,3,4,5).map(x => add(3, x)) |
|
367 |
||
368 |
def add2(x: Int)(y: Int) = x + y |
|
369 |
||
370 |
List(1,2,3,4,5).map(add2(3)) |
|
371 |
||
372 |
val a3 : Int => Int = add2(3) |
|
373 |
||
374 |
// currying helps sometimes with type inference |
|
375 |
||
376 |
def find[A](xs: List[A])(pred: A => Boolean): Option[A] = {
|
|
377 |
xs match {
|
|
378 |
case Nil => None |
|
379 |
case hd :: tl => |
|
380 |
if (pred(hd)) Some(hd) else find(tl)(pred) |
|
381 |
} |
|
382 |
} |
|
383 |
||
384 |
find(List(1, 2, 3))(x => x % 2 == 0) |
|
385 |
||
386 |
// Source.fromURL(url)(encoding) |
|
387 |
// Source.fromFile(name)(encoding) |
|
| 325 | 388 |
|
389 |
||
| 384 | 390 |
|
| 382 | 391 |
|
392 |
||
393 |
||
394 |
||
| 325 | 395 |
// Sudoku |
396 |
//======== |
|
397 |
||
398 |
// THE POINT OF THIS CODE IS NOT TO BE SUPER |
|
399 |
// EFFICIENT AND FAST, just explaining exhaustive |
|
400 |
// depth-first search |
|
401 |
||
402 |
||
403 |
val game0 = """.14.6.3.. |
|
404 |
|62...4..9 |
|
405 |
|.8..5.6.. |
|
406 |
|.6.2....3 |
|
407 |
|.7..1..5. |
|
408 |
|5....9.6. |
|
409 |
|..6.2..3. |
|
410 |
|1..5...92 |
|
411 |
|..7.9.41.""".stripMargin.replaceAll("\\n", "")
|
|
412 |
||
| 383 | 413 |
|
| 326 | 414 |
|
| 325 | 415 |
type Pos = (Int, Int) |
416 |
val EmptyValue = '.' |
|
417 |
val MaxValue = 9 |
|
418 |
||
| 383 | 419 |
def pretty(game: String): String = |
420 |
"\n" + (game.grouped(MaxValue).mkString("\n"))
|
|
421 |
||
422 |
pretty(game0) |
|
423 |
||
424 |
||
| 325 | 425 |
val allValues = "123456789".toList |
426 |
val indexes = (0 to 8).toList |
|
427 |
||
428 |
def empty(game: String) = game.indexOf(EmptyValue) |
|
429 |
def isDone(game: String) = empty(game) == -1 |
|
| 383 | 430 |
def emptyPosition(game: String) = {
|
431 |
val e = empty(game) |
|
432 |
(e % MaxValue, e / MaxValue) |
|
433 |
} |
|
| 325 | 434 |
|
435 |
def get_row(game: String, y: Int) = |
|
436 |
indexes.map(col => game(y * MaxValue + col)) |
|
437 |
def get_col(game: String, x: Int) = |
|
438 |
indexes.map(row => game(x + row * MaxValue)) |
|
439 |
||
| 383 | 440 |
//get_row(game0, 0) |
441 |
//get_row(game0, 1) |
|
442 |
//get_col(game0, 0) |
|
| 326 | 443 |
|
| 325 | 444 |
def get_box(game: String, pos: Pos): List[Char] = {
|
445 |
def base(p: Int): Int = (p / 3) * 3 |
|
446 |
val x0 = base(pos._1) |
|
447 |
val y0 = base(pos._2) |
|
448 |
val ys = (y0 until y0 + 3).toList |
|
| 383 | 449 |
(x0 until x0 + 3).toList |
450 |
.flatMap(x => ys.map(y => game(x + y * MaxValue))) |
|
| 325 | 451 |
} |
452 |
||
| 383 | 453 |
|
| 325 | 454 |
//get_box(game0, (3, 1)) |
455 |
||
456 |
||
457 |
// this is not mutable!! |
|
458 |
def update(game: String, pos: Int, value: Char): String = |
|
459 |
game.updated(pos, value) |
|
460 |
||
461 |
def toAvoid(game: String, pos: Pos): List[Char] = |
|
| 383 | 462 |
(get_col(game, pos._1) ++ |
463 |
get_row(game, pos._2) ++ |
|
464 |
get_box(game, pos)) |
|
| 325 | 465 |
|
466 |
def candidates(game: String, pos: Pos): List[Char] = |
|
467 |
allValues.diff(toAvoid(game, pos)) |
|
468 |
||
469 |
//candidates(game0, (0,0)) |
|
470 |
||
471 |
||
472 |
def search(game: String): List[String] = {
|
|
473 |
if (isDone(game)) List(game) |
|
474 |
else {
|
|
475 |
val cs = candidates(game, emptyPosition(game)) |
|
| 383 | 476 |
cs.map(c => search(update(game, empty(game), c))).flatten |
| 325 | 477 |
} |
478 |
} |
|
479 |
||
| 383 | 480 |
pretty(game0) |
| 325 | 481 |
search(game0).map(pretty) |
482 |
||
483 |
val game1 = """23.915... |
|
484 |
|...2..54. |
|
485 |
|6.7...... |
|
486 |
|..1.....9 |
|
487 |
|89.5.3.17 |
|
488 |
|5.....6.. |
|
489 |
|......9.5 |
|
490 |
|.16..7... |
|
491 |
|...329..1""".stripMargin.replaceAll("\\n", "")
|
|
492 |
||
493 |
search(game1).map(pretty) |
|
494 |
||
495 |
// a game that is in the hard category |
|
496 |
val game2 = """8........ |
|
497 |
|..36..... |
|
498 |
|.7..9.2.. |
|
499 |
|.5...7... |
|
500 |
|....457.. |
|
501 |
|...1...3. |
|
502 |
|..1....68 |
|
503 |
|..85...1. |
|
504 |
|.9....4..""".stripMargin.replaceAll("\\n", "")
|
|
505 |
||
506 |
search(game2).map(pretty) |
|
507 |
||
508 |
// game with multiple solutions |
|
509 |
val game3 = """.8...9743 |
|
510 |
|.5...8.1. |
|
511 |
|.1....... |
|
512 |
|8....5... |
|
513 |
|...8.4... |
|
514 |
|...3....6 |
|
515 |
|.......7. |
|
516 |
|.3.5...8. |
|
517 |
|9724...5.""".stripMargin.replaceAll("\\n", "")
|
|
518 |
||
519 |
search(game3).map(pretty).foreach(println) |
|
520 |
||
521 |
// for measuring time |
|
522 |
def time_needed[T](i: Int, code: => T) = {
|
|
523 |
val start = System.nanoTime() |
|
524 |
for (j <- 1 to i) code |
|
525 |
val end = System.nanoTime() |
|
526 |
s"${(end - start) / 1.0e9} secs"
|
|
527 |
} |
|
528 |
||
529 |
time_needed(1, search(game2)) |
|
530 |
||
531 |
||
532 |
||
| 384 | 533 |
// tail recursive version that searches |
534 |
// for all Sudoku solutions |
|
| 325 | 535 |
import scala.annotation.tailrec |
536 |
||
537 |
@tailrec |
|
| 384 | 538 |
def searchT(games: List[String], sols: List[String]): List[String] = |
539 |
games match {
|
|
540 |
case Nil => sols |
|
541 |
case game::rest => {
|
|
542 |
if (isDone(game)) searchT(rest, game::sols) |
|
543 |
else {
|
|
544 |
val cs = candidates(game, emptyPosition(game)) |
|
| 491 | 545 |
searchT(cs.map(c => update(game, empty(game), c)) |
546 |
::: rest, sols) |
|
| 384 | 547 |
} |
548 |
} |
|
549 |
} |
|
| 325 | 550 |
|
551 |
searchT(List(game3), List()).map(pretty) |
|
552 |
||
553 |
||
554 |
// tail recursive version that searches |
|
555 |
// for a single solution |
|
556 |
||
557 |
def search1T(games: List[String]): Option[String] = games match {
|
|
558 |
case Nil => None |
|
559 |
case game::rest => {
|
|
560 |
if (isDone(game)) Some(game) |
|
561 |
else {
|
|
562 |
val cs = candidates(game, emptyPosition(game)) |
|
563 |
search1T(cs.map(c => update(game, empty(game), c)) ::: rest) |
|
564 |
} |
|
565 |
} |
|
566 |
} |
|
567 |
||
568 |
search1T(List(game3)).map(pretty) |
|
569 |
time_needed(1, search1T(List(game3))) |
|
570 |
time_needed(1, search1T(List(game2))) |
|
571 |
||
572 |
// game with multiple solutions |
|
573 |
val game3 = """.8...9743 |
|
574 |
|.5...8.1. |
|
575 |
|.1....... |
|
576 |
|8....5... |
|
577 |
|...8.4... |
|
578 |
|...3....6 |
|
579 |
|.......7. |
|
580 |
|.3.5...8. |
|
581 |
|9724...5.""".stripMargin.replaceAll("\\n", "")
|
|
582 |
||
583 |
searchT(List(game3), Nil).map(pretty) |
|
584 |
search1T(List(game3)).map(pretty) |
|
585 |
||
586 |
||
587 |
||
| 222 | 588 |
|
589 |
||
590 |
||
| 325 | 591 |
// Cool Stuff in Scala |
592 |
//===================== |
|
593 |
||
594 |
||
595 |
// Implicits or How to Pimp your Library |
|
596 |
//====================================== |
|
597 |
// |
|
598 |
// For example adding your own methods to Strings: |
|
599 |
// Imagine you want to increment strings, like |
|
600 |
// |
|
601 |
// "HAL".increment |
|
602 |
// |
|
603 |
// you can avoid ugly fudges, like a MyString, by |
|
| 491 | 604 |
// using an extension. |
| 325 | 605 |
|
606 |
||
| 491 | 607 |
extension (s: String) {
|
| 325 | 608 |
def increment = s.map(c => (c + 1).toChar) |
609 |
} |
|
610 |
||
| 452 | 611 |
"HAL".increment |
| 325 | 612 |
|
613 |
||
614 |
||
|
381
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
615 |
|
| 325 | 616 |
|
617 |
import scala.concurrent.duration.{TimeUnit,SECONDS,MINUTES}
|
|
618 |
||
619 |
case class Duration(time: Long, unit: TimeUnit) {
|
|
620 |
def +(o: Duration) = |
|
621 |
Duration(time + unit.convert(o.time, o.unit), unit) |
|
622 |
} |
|
623 |
||
| 491 | 624 |
extension (that: Int) {
|
|
381
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
625 |
def seconds = Duration(that, SECONDS) |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
626 |
def minutes = Duration(that, MINUTES) |
| 325 | 627 |
} |
628 |
||
629 |
5.seconds + 2.minutes //Duration(125L, SECONDS ) |
|
630 |
2.minutes + 60.seconds |
|
631 |
||
632 |
||
633 |
||
634 |
||
635 |
// Regular expressions - the power of DSLs in Scala |
|
636 |
//================================================== |
|
637 |
||
| 507 | 638 |
enum Rexp {
|
639 |
case ZERO // nothing |
|
640 |
case ONE // the empty string |
|
641 |
case CHAR(c: Char) // a character c |
|
642 |
case ALT(r1: Rexp, r2: Rexp) // alternative r1 + r2 |
|
643 |
case SEQ(r1: Rexp, r2: Rexp) // sequence r1 . r2 |
|
644 |
case STAR(r: Rexp) // star r* |
|
645 |
} |
|
646 |
import Rexp._ |
|
| 325 | 647 |
|
648 |
// writing (ab)* in the format above is |
|
649 |
// tedious |
|
650 |
val r0 = STAR(SEQ(CHAR('a'), CHAR('b')))
|
|
651 |
||
652 |
||
653 |
// some convenience for typing in regular expressions |
|
654 |
import scala.language.implicitConversions |
|
655 |
||
656 |
def charlist2rexp(s: List[Char]): Rexp = s match {
|
|
657 |
case Nil => ONE |
|
658 |
case c::Nil => CHAR(c) |
|
659 |
case c::s => SEQ(CHAR(c), charlist2rexp(s)) |
|
660 |
} |
|
| 326 | 661 |
|
| 491 | 662 |
given Conversion[String, Rexp] = |
663 |
(s => charlist2rexp(s.toList)) |
|
| 325 | 664 |
|
| 415 | 665 |
val r1 = STAR("ab")
|
|
381
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
666 |
val r2 = STAR("hello") | STAR("world")
|
| 325 | 667 |
|
668 |
||
| 491 | 669 |
extension (r: Rexp) {
|
| 325 | 670 |
def | (s: Rexp) = ALT(r, s) |
671 |
def % = STAR(r) |
|
672 |
def ~ (s: Rexp) = SEQ(r, s) |
|
673 |
} |
|
674 |
||
| 491 | 675 |
//example regular expressions |
| 325 | 676 |
|
| 491 | 677 |
val rex = "ab".% |
|
381
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
678 |
|
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
679 |
|
| 326 | 680 |
val digit = ("0" | "1" | "2" | "3" | "4" |
|
681 |
"5" | "6" | "7" | "8" | "9") |
|
| 325 | 682 |
val sign = "+" | "-" | "" |
683 |
val number = sign ~ digit ~ digit.% |
|
684 |
||
685 |
||
| 507 | 686 |
extension (n: Int) {
|
687 |
def ++ = n + 1 |
|
688 |
} |
|
| 325 | 689 |
|
| 507 | 690 |
def --(n: Int) = n - 1 |
691 |
||
692 |
val n = 3 |
|
693 |
val m = (n.++) |
|
694 |
val k = --(n) |
|
|
381
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
695 |
|
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
696 |
// In mandelbrot.scala I used complex (imaginary) numbers |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
697 |
// and implemented the usual arithmetic operations for complex |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
698 |
// numbers. |
| 325 | 699 |
|
|
381
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
700 |
case class Complex(re: Double, im: Double) {
|
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
701 |
// represents the complex number re + im * i |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
702 |
def +(that: Complex) = Complex(this.re + that.re, this.im + that.im) |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
703 |
def -(that: Complex) = Complex(this.re - that.re, this.im - that.im) |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
704 |
def *(that: Complex) = Complex(this.re * that.re - this.im * that.im, |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
705 |
this.re * that.im + that.re * this.im) |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
706 |
def *(that: Double) = Complex(this.re * that, this.im * that) |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
707 |
def abs = Math.sqrt(this.re * this.re + this.im * this.im) |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
708 |
} |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
709 |
|
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
710 |
val test = Complex(1, 2) + Complex (3, 4) |
| 222 | 711 |
|
| 325 | 712 |
|
|
381
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
713 |
// ...to allow the notation n + m * i |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
714 |
import scala.language.implicitConversions |
| 325 | 715 |
|
|
381
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
716 |
val i = Complex(0, 1) |
| 491 | 717 |
given Conversion[Double, Complex] = (re: Double) => Complex(re, 0) |
| 222 | 718 |
|
|
381
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
719 |
val inum1 = -2.0 + -1.5 * i |
|
6c2792a3e00d
updated duration class
Christian Urban <christian.urban@kcl.ac.uk>
parents:
380
diff
changeset
|
720 |
val inum2 = 1.0 + 1.5 * i |