222
|
1 |
// Scala Lecture 4
|
|
2 |
//=================
|
|
3 |
|
|
4 |
|
325
|
5 |
// expressions (essentially trees)
|
|
6 |
|
|
7 |
abstract class Exp
|
|
8 |
case class N(n: Int) extends Exp // for numbers
|
|
9 |
case class Plus(e1: Exp, e2: Exp) extends Exp
|
|
10 |
case class Times(e1: Exp, e2: Exp) extends Exp
|
|
11 |
|
|
12 |
def string(e: Exp) : String = e match {
|
|
13 |
case N(n) => s"$n"
|
|
14 |
case Plus(e1, e2) => s"(${string(e1)} + ${string(e2)})"
|
|
15 |
case Times(e1, e2) => s"(${string(e1)} * ${string(e2)})"
|
|
16 |
}
|
|
17 |
|
|
18 |
val e = Plus(N(9), Times(N(3), N(4)))
|
|
19 |
println(string(e))
|
|
20 |
|
|
21 |
def eval(e: Exp) : Int = e match {
|
|
22 |
case N(n) => n
|
|
23 |
case Plus(e1, e2) => eval(e1) + eval(e2)
|
|
24 |
case Times(e1, e2) => eval(e1) * eval(e2)
|
|
25 |
}
|
|
26 |
|
|
27 |
println(eval(e))
|
|
28 |
|
|
29 |
// simplification rules:
|
|
30 |
// e + 0, 0 + e => e
|
|
31 |
// e * 0, 0 * e => 0
|
|
32 |
// e * 1, 1 * e => e
|
326
|
33 |
//
|
|
34 |
// (....0 ....)
|
325
|
35 |
|
|
36 |
def simp(e: Exp) : Exp = e match {
|
|
37 |
case N(n) => N(n)
|
|
38 |
case Plus(e1, e2) => (simp(e1), simp(e2)) match {
|
|
39 |
case (N(0), e2s) => e2s
|
|
40 |
case (e1s, N(0)) => e1s
|
|
41 |
case (e1s, e2s) => Plus(e1s, e2s)
|
|
42 |
}
|
|
43 |
case Times(e1, e2) => (simp(e1), simp(e2)) match {
|
|
44 |
case (N(0), _) => N(0)
|
|
45 |
case (_, N(0)) => N(0)
|
|
46 |
case (N(1), e2s) => e2s
|
|
47 |
case (e1s, N(1)) => e1s
|
|
48 |
case (e1s, e2s) => Times(e1s, e2s)
|
|
49 |
}
|
|
50 |
}
|
|
51 |
|
|
52 |
|
|
53 |
val e2 = Times(Plus(N(0), N(1)), Plus(N(0), N(9)))
|
|
54 |
println(string(e2))
|
|
55 |
println(string(simp(e2)))
|
|
56 |
|
|
57 |
|
|
58 |
// Tokens and Reverse Polish Notation
|
|
59 |
abstract class Token
|
|
60 |
case class T(n: Int) extends Token
|
|
61 |
case object PL extends Token
|
|
62 |
case object TI extends Token
|
|
63 |
|
|
64 |
// transfroming an Exp into a list of tokens
|
|
65 |
def rp(e: Exp) : List[Token] = e match {
|
|
66 |
case N(n) => List(T(n))
|
|
67 |
case Plus(e1, e2) => rp(e1) ::: rp(e2) ::: List(PL)
|
|
68 |
case Times(e1, e2) => rp(e1) ::: rp(e2) ::: List(TI)
|
|
69 |
}
|
|
70 |
println(string(e2))
|
|
71 |
println(rp(e2))
|
|
72 |
|
326
|
73 |
def comp(ls: List[Token], st: List[Int] = Nil) : Int = (ls, st) match {
|
325
|
74 |
case (Nil, st) => st.head
|
|
75 |
case (T(n)::rest, st) => comp(rest, n::st)
|
|
76 |
case (PL::rest, n1::n2::st) => comp(rest, n1 + n2::st)
|
|
77 |
case (TI::rest, n1::n2::st) => comp(rest, n1 * n2::st)
|
|
78 |
}
|
|
79 |
|
326
|
80 |
comp(rp(e))
|
325
|
81 |
|
|
82 |
def proc(s: String) : Token = s match {
|
|
83 |
case "+" => PL
|
|
84 |
case "*" => TI
|
|
85 |
case _ => T(s.toInt)
|
|
86 |
}
|
|
87 |
|
|
88 |
comp("1 2 + 4 * 5 + 3 +".split(" ").toList.map(proc), Nil)
|
|
89 |
|
|
90 |
|
|
91 |
|
|
92 |
|
|
93 |
// Sudoku
|
|
94 |
//========
|
|
95 |
|
|
96 |
// THE POINT OF THIS CODE IS NOT TO BE SUPER
|
|
97 |
// EFFICIENT AND FAST, just explaining exhaustive
|
|
98 |
// depth-first search
|
|
99 |
|
|
100 |
|
|
101 |
val game0 = """.14.6.3..
|
|
102 |
|62...4..9
|
|
103 |
|.8..5.6..
|
|
104 |
|.6.2....3
|
|
105 |
|.7..1..5.
|
|
106 |
|5....9.6.
|
|
107 |
|..6.2..3.
|
|
108 |
|1..5...92
|
|
109 |
|..7.9.41.""".stripMargin.replaceAll("\\n", "")
|
|
110 |
|
326
|
111 |
candidates(game0, (0, 0))
|
|
112 |
|
325
|
113 |
type Pos = (Int, Int)
|
|
114 |
val EmptyValue = '.'
|
|
115 |
val MaxValue = 9
|
|
116 |
|
|
117 |
val allValues = "123456789".toList
|
|
118 |
val indexes = (0 to 8).toList
|
|
119 |
|
|
120 |
|
|
121 |
def empty(game: String) = game.indexOf(EmptyValue)
|
|
122 |
def isDone(game: String) = empty(game) == -1
|
|
123 |
def emptyPosition(game: String) =
|
|
124 |
(empty(game) % MaxValue, empty(game) / MaxValue)
|
|
125 |
|
|
126 |
|
|
127 |
def get_row(game: String, y: Int) =
|
|
128 |
indexes.map(col => game(y * MaxValue + col))
|
|
129 |
def get_col(game: String, x: Int) =
|
|
130 |
indexes.map(row => game(x + row * MaxValue))
|
|
131 |
|
326
|
132 |
get_row(game0, 0)
|
|
133 |
|
325
|
134 |
def get_box(game: String, pos: Pos): List[Char] = {
|
|
135 |
def base(p: Int): Int = (p / 3) * 3
|
|
136 |
val x0 = base(pos._1)
|
|
137 |
val y0 = base(pos._2)
|
|
138 |
val ys = (y0 until y0 + 3).toList
|
|
139 |
(x0 until x0 + 3).toList.flatMap(x => ys.map(y => game(x + y * MaxValue)))
|
|
140 |
}
|
|
141 |
|
|
142 |
//get_row(game0, 0)
|
|
143 |
//get_row(game0, 1)
|
|
144 |
//get_col(game0, 0)
|
|
145 |
//get_box(game0, (3, 1))
|
|
146 |
|
|
147 |
|
|
148 |
// this is not mutable!!
|
|
149 |
def update(game: String, pos: Int, value: Char): String =
|
|
150 |
game.updated(pos, value)
|
|
151 |
|
|
152 |
def toAvoid(game: String, pos: Pos): List[Char] =
|
|
153 |
(get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos))
|
|
154 |
|
|
155 |
def candidates(game: String, pos: Pos): List[Char] =
|
|
156 |
allValues.diff(toAvoid(game, pos))
|
|
157 |
|
|
158 |
//candidates(game0, (0,0))
|
|
159 |
|
|
160 |
def pretty(game: String): String =
|
|
161 |
"\n" + (game.sliding(MaxValue, MaxValue).mkString("\n"))
|
|
162 |
|
|
163 |
def search(game: String): List[String] = {
|
|
164 |
if (isDone(game)) List(game)
|
|
165 |
else {
|
|
166 |
val cs = candidates(game, emptyPosition(game))
|
|
167 |
cs.map(c => search(update(game, empty(game), c))).toList.flatten
|
|
168 |
}
|
|
169 |
}
|
|
170 |
|
326
|
171 |
List(List("sol1"), List("sol2", "sol3")).flatten
|
|
172 |
|
325
|
173 |
search(game0).map(pretty)
|
|
174 |
|
|
175 |
val game1 = """23.915...
|
|
176 |
|...2..54.
|
|
177 |
|6.7......
|
|
178 |
|..1.....9
|
|
179 |
|89.5.3.17
|
|
180 |
|5.....6..
|
|
181 |
|......9.5
|
|
182 |
|.16..7...
|
|
183 |
|...329..1""".stripMargin.replaceAll("\\n", "")
|
|
184 |
|
|
185 |
search(game1).map(pretty)
|
|
186 |
|
|
187 |
// a game that is in the hard category
|
|
188 |
val game2 = """8........
|
|
189 |
|..36.....
|
|
190 |
|.7..9.2..
|
|
191 |
|.5...7...
|
|
192 |
|....457..
|
|
193 |
|...1...3.
|
|
194 |
|..1....68
|
|
195 |
|..85...1.
|
|
196 |
|.9....4..""".stripMargin.replaceAll("\\n", "")
|
|
197 |
|
|
198 |
search(game2).map(pretty)
|
|
199 |
|
|
200 |
// game with multiple solutions
|
|
201 |
val game3 = """.8...9743
|
|
202 |
|.5...8.1.
|
|
203 |
|.1.......
|
|
204 |
|8....5...
|
|
205 |
|...8.4...
|
|
206 |
|...3....6
|
|
207 |
|.......7.
|
|
208 |
|.3.5...8.
|
|
209 |
|9724...5.""".stripMargin.replaceAll("\\n", "")
|
|
210 |
|
|
211 |
search(game3).map(pretty).foreach(println)
|
|
212 |
|
|
213 |
// for measuring time
|
|
214 |
def time_needed[T](i: Int, code: => T) = {
|
|
215 |
val start = System.nanoTime()
|
|
216 |
for (j <- 1 to i) code
|
|
217 |
val end = System.nanoTime()
|
|
218 |
s"${(end - start) / 1.0e9} secs"
|
|
219 |
}
|
|
220 |
|
|
221 |
time_needed(1, search(game2))
|
|
222 |
|
|
223 |
|
|
224 |
|
|
225 |
// Tail recursion
|
|
226 |
//================
|
|
227 |
|
326
|
228 |
@tailrec
|
|
229 |
def fact(n: BigInt): BigInt =
|
325
|
230 |
if (n == 0) 1 else n * fact(n - 1)
|
|
231 |
|
|
232 |
|
326
|
233 |
fact(10)
|
|
234 |
fact(1000)
|
|
235 |
fact(100000)
|
325
|
236 |
|
|
237 |
def factB(n: BigInt): BigInt =
|
|
238 |
if (n == 0) 1 else n * factB(n - 1)
|
|
239 |
|
326
|
240 |
def factT(n: BigInt, acc: BigInt): BigInt =
|
|
241 |
if (n == 0) acc else factT(n - 1, n * acc)
|
|
242 |
|
|
243 |
|
325
|
244 |
factB(1000)
|
|
245 |
|
|
246 |
|
326
|
247 |
|
325
|
248 |
|
|
249 |
factT(10, 1)
|
326
|
250 |
println(factT(500000, 1))
|
|
251 |
|
|
252 |
|
|
253 |
|
|
254 |
|
325
|
255 |
|
|
256 |
// there is a flag for ensuring a function is tail recursive
|
|
257 |
import scala.annotation.tailrec
|
|
258 |
|
|
259 |
@tailrec
|
|
260 |
def factT(n: BigInt, acc: BigInt): BigInt =
|
|
261 |
if (n == 0) acc else factT(n - 1, n * acc)
|
|
262 |
|
|
263 |
factT(100000, 1)
|
|
264 |
|
|
265 |
// for tail-recursive functions the Scala compiler
|
|
266 |
// generates loop-like code, which does not need
|
|
267 |
// to allocate stack-space in each recursive
|
|
268 |
// call; Scala can do this only for tail-recursive
|
|
269 |
// functions
|
|
270 |
|
|
271 |
// tail recursive version that searches
|
|
272 |
// for all Sudoku solutions
|
|
273 |
|
326
|
274 |
@tailrec
|
325
|
275 |
def searchT(games: List[String], sols: List[String]): List[String] = games match {
|
|
276 |
case Nil => sols
|
|
277 |
case game::rest => {
|
|
278 |
if (isDone(game)) searchT(rest, game::sols)
|
|
279 |
else {
|
|
280 |
val cs = candidates(game, emptyPosition(game))
|
|
281 |
searchT(cs.map(c => update(game, empty(game), c)) ::: rest, sols)
|
|
282 |
}
|
|
283 |
}
|
|
284 |
}
|
|
285 |
|
|
286 |
searchT(List(game3), List()).map(pretty)
|
|
287 |
|
|
288 |
|
|
289 |
// tail recursive version that searches
|
|
290 |
// for a single solution
|
|
291 |
|
|
292 |
def search1T(games: List[String]): Option[String] = games match {
|
|
293 |
case Nil => None
|
|
294 |
case game::rest => {
|
|
295 |
if (isDone(game)) Some(game)
|
|
296 |
else {
|
|
297 |
val cs = candidates(game, emptyPosition(game))
|
|
298 |
search1T(cs.map(c => update(game, empty(game), c)) ::: rest)
|
|
299 |
}
|
|
300 |
}
|
|
301 |
}
|
|
302 |
|
|
303 |
search1T(List(game3)).map(pretty)
|
|
304 |
time_needed(1, search1T(List(game3)))
|
|
305 |
time_needed(1, search1T(List(game2)))
|
|
306 |
|
|
307 |
// game with multiple solutions
|
|
308 |
val game3 = """.8...9743
|
|
309 |
|.5...8.1.
|
|
310 |
|.1.......
|
|
311 |
|8....5...
|
|
312 |
|...8.4...
|
|
313 |
|...3....6
|
|
314 |
|.......7.
|
|
315 |
|.3.5...8.
|
|
316 |
|9724...5.""".stripMargin.replaceAll("\\n", "")
|
|
317 |
|
|
318 |
searchT(List(game3), Nil).map(pretty)
|
|
319 |
search1T(List(game3)).map(pretty)
|
|
320 |
|
|
321 |
// Moral: Whenever a recursive function is resource-critical
|
326
|
322 |
// (i.e. works with a large recursion depth), then you need to
|
325
|
323 |
// write it in tail-recursive fashion.
|
|
324 |
//
|
|
325 |
// Unfortuantely, Scala because of current limitations in
|
|
326 |
// the JVM is not as clever as other functional languages. It can
|
|
327 |
// only optimise "self-tail calls". This excludes the cases of
|
|
328 |
// multiple functions making tail calls to each other. Well,
|
|
329 |
// nothing is perfect.
|
|
330 |
|
|
331 |
|
|
332 |
|
|
333 |
|
222
|
334 |
|
|
335 |
|
|
336 |
|
325
|
337 |
// Cool Stuff in Scala
|
|
338 |
//=====================
|
|
339 |
|
|
340 |
|
|
341 |
// Implicits or How to Pimp your Library
|
|
342 |
//======================================
|
|
343 |
//
|
|
344 |
// For example adding your own methods to Strings:
|
|
345 |
// Imagine you want to increment strings, like
|
|
346 |
//
|
|
347 |
// "HAL".increment
|
|
348 |
//
|
|
349 |
// you can avoid ugly fudges, like a MyString, by
|
|
350 |
// using implicit conversions.
|
|
351 |
|
|
352 |
|
|
353 |
implicit class MyString(s: String) {
|
|
354 |
def increment = s.map(c => (c + 1).toChar)
|
|
355 |
}
|
|
356 |
|
|
357 |
"HAL".increment
|
|
358 |
|
|
359 |
|
|
360 |
// Abstract idea:
|
|
361 |
// In that version implicit conversions were used to solve the
|
|
362 |
// late extension problem; namely, given a class C and a class T,
|
|
363 |
// how to have C extend T without touching or recompiling C.
|
|
364 |
// Conversions add a wrapper when a member of T is requested
|
|
365 |
// from an instance of C.
|
|
366 |
|
|
367 |
//Another example (TimeUnit in 2.13?)
|
|
368 |
|
|
369 |
import scala.concurrent.duration.{TimeUnit,SECONDS,MINUTES}
|
|
370 |
|
|
371 |
case class Duration(time: Long, unit: TimeUnit) {
|
|
372 |
def +(o: Duration) =
|
|
373 |
Duration(time + unit.convert(o.time, o.unit), unit)
|
|
374 |
}
|
|
375 |
|
|
376 |
implicit class Int2Duration(that: Int) {
|
|
377 |
def seconds = new Duration(that, SECONDS)
|
|
378 |
def minutes = new Duration(that, MINUTES)
|
|
379 |
}
|
|
380 |
|
|
381 |
5.seconds + 2.minutes //Duration(125L, SECONDS )
|
|
382 |
2.minutes + 60.seconds
|
|
383 |
|
|
384 |
|
|
385 |
|
|
386 |
|
|
387 |
// Regular expressions - the power of DSLs in Scala
|
|
388 |
//==================================================
|
|
389 |
|
|
390 |
abstract class Rexp
|
|
391 |
case object ZERO extends Rexp // nothing
|
|
392 |
case object ONE extends Rexp // the empty string
|
|
393 |
case class CHAR(c: Char) extends Rexp // a character c
|
|
394 |
case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative r1 + r2
|
|
395 |
case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence r1 . r2
|
|
396 |
case class STAR(r: Rexp) extends Rexp // star r*
|
|
397 |
|
|
398 |
|
|
399 |
|
|
400 |
// writing (ab)* in the format above is
|
|
401 |
// tedious
|
|
402 |
val r0 = STAR(SEQ(CHAR('a'), CHAR('b')))
|
|
403 |
|
|
404 |
|
|
405 |
// some convenience for typing in regular expressions
|
|
406 |
import scala.language.implicitConversions
|
|
407 |
import scala.language.reflectiveCalls
|
|
408 |
|
|
409 |
def charlist2rexp(s: List[Char]): Rexp = s match {
|
|
410 |
case Nil => ONE
|
|
411 |
case c::Nil => CHAR(c)
|
|
412 |
case c::s => SEQ(CHAR(c), charlist2rexp(s))
|
|
413 |
}
|
326
|
414 |
|
325
|
415 |
implicit def string2rexp(s: String): Rexp =
|
|
416 |
charlist2rexp(s.toList)
|
|
417 |
|
326
|
418 |
"(a|b)"
|
325
|
419 |
|
|
420 |
val r1 = STAR("ab")
|
326
|
421 |
val r2 = (STAR("ab")) | (STAR("ba"))
|
325
|
422 |
val r3 = STAR(SEQ("ab", ALT("a", "b")))
|
|
423 |
|
|
424 |
implicit def RexpOps (r: Rexp) = new {
|
|
425 |
def | (s: Rexp) = ALT(r, s)
|
|
426 |
def % = STAR(r)
|
|
427 |
def ~ (s: Rexp) = SEQ(r, s)
|
|
428 |
}
|
|
429 |
|
|
430 |
implicit def stringOps (s: String) = new {
|
|
431 |
def | (r: Rexp) = ALT(s, r)
|
|
432 |
def | (r: String) = ALT(s, r)
|
|
433 |
def % = STAR(s)
|
|
434 |
def ~ (r: Rexp) = SEQ(s, r)
|
|
435 |
def ~ (r: String) = SEQ(s, r)
|
|
436 |
}
|
|
437 |
|
|
438 |
//example regular expressions
|
326
|
439 |
val digit = ("0" | "1" | "2" | "3" | "4" |
|
|
440 |
"5" | "6" | "7" | "8" | "9")
|
325
|
441 |
val sign = "+" | "-" | ""
|
|
442 |
val number = sign ~ digit ~ digit.%
|
|
443 |
|
|
444 |
|
|
445 |
|
|
446 |
// Mind-Blowing Regular Expressions
|
|
447 |
|
222
|
448 |
// same examples using the internal regexes
|
|
449 |
val evil = "(a*)*b"
|
|
450 |
|
325
|
451 |
|
|
452 |
println("a" * 100)
|
|
453 |
|
326
|
454 |
("a" * 10000).matches(evil)
|
222
|
455 |
("a" * 10).matches(evil)
|
|
456 |
("a" * 10000).matches(evil)
|
|
457 |
("a" * 20000).matches(evil)
|
226
|
458 |
("a" * 50000).matches(evil)
|
222
|
459 |
|
326
|
460 |
time_needed(1, ("a" * 50000).matches(evil))
|