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