51
|
1 |
// Scala Lecture 2
|
|
2 |
//=================
|
|
3 |
|
|
4 |
|
|
5 |
// Option type
|
|
6 |
//=============
|
53
|
7 |
|
57
|
8 |
//in Java if something unusually happens, you return null;
|
53
|
9 |
//in Scala you use Option
|
|
10 |
// - if the value is present, you use Some(value)
|
|
11 |
// - if no value is present, you use None
|
|
12 |
|
|
13 |
|
|
14 |
List(7,2,3,4,5,6).find(_ < 4)
|
|
15 |
List(5,6,7,8,9).find(_ < 4)
|
|
16 |
|
58
|
17 |
|
|
18 |
// Values in types
|
|
19 |
//
|
|
20 |
// Boolean:
|
|
21 |
// Int:
|
|
22 |
// String:
|
|
23 |
//
|
|
24 |
// Option[String]:
|
|
25 |
//
|
|
26 |
|
|
27 |
|
51
|
28 |
val lst = List(None, Some(1), Some(2), None, Some(3))
|
|
29 |
|
|
30 |
lst.flatten
|
53
|
31 |
|
51
|
32 |
Some(1).get
|
|
33 |
|
53
|
34 |
Some(1).isDefined
|
|
35 |
None.isDefined
|
|
36 |
|
51
|
37 |
val ps = List((3, 0), (3, 2), (4, 2), (2, 0), (1, 0), (1, 1))
|
|
38 |
|
|
39 |
for ((x, y) <- ps) yield {
|
|
40 |
if (y == 0) None else Some(x / y)
|
|
41 |
}
|
|
42 |
|
57
|
43 |
// getOrElse is for setting a default value
|
53
|
44 |
|
|
45 |
val lst = List(None, Some(1), Some(2), None, Some(3))
|
57
|
46 |
for (x <- lst) yield x.getOrElse(0)
|
|
47 |
|
|
48 |
|
53
|
49 |
|
|
50 |
|
58
|
51 |
// error handling with Option (no exceptions)
|
57
|
52 |
//
|
|
53 |
// Try(something).getOrElse(what_to_do_in_an_exception)
|
|
54 |
//
|
53
|
55 |
import scala.util._
|
|
56 |
import io.Source
|
|
57 |
|
57
|
58 |
Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString
|
53
|
59 |
|
|
60 |
Try(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString).getOrElse("")
|
|
61 |
|
|
62 |
Try(Some(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString)).getOrElse(None)
|
|
63 |
|
57
|
64 |
// a function that turns strings into numbers
|
53
|
65 |
Integer.parseInt("12u34")
|
|
66 |
|
|
67 |
def get_me_an_int(s: String): Option[Int] =
|
|
68 |
Try(Some(Integer.parseInt(s))).getOrElse(None)
|
|
69 |
|
|
70 |
val lst = List("12345", "foo", "5432", "bar", "x21")
|
|
71 |
for (x <- lst) yield get_me_an_int(x)
|
|
72 |
|
|
73 |
// summing all the numbers
|
|
74 |
val sum = lst.flatMap(get_me_an_int(_)).sum
|
|
75 |
|
|
76 |
|
|
77 |
// This may not look any better than working with null in Java, but to
|
|
78 |
// see the value, you have to put yourself in the shoes of the
|
|
79 |
// consumer of the get_me_an_int function, and imagine you didn't
|
|
80 |
// write that function.
|
|
81 |
//
|
|
82 |
// In Java, if you didn't write this function, you'd have to depend on
|
57
|
83 |
// the Javadoc of the get_me_an_int. If you didn't look at the Javadoc,
|
|
84 |
// you might not know that get_me_an_int could return a null, and your
|
|
85 |
// code could potentially throw a NullPointerException.
|
53
|
86 |
|
|
87 |
|
|
88 |
|
58
|
89 |
// even Scala is not immune to problems like this:
|
|
90 |
|
|
91 |
List(5,6,7,8,9).indexOf(7)
|
|
92 |
|
|
93 |
|
|
94 |
|
|
95 |
|
|
96 |
|
53
|
97 |
// Type abbreviations
|
|
98 |
//====================
|
|
99 |
|
|
100 |
// some syntactic convenience
|
|
101 |
type Pos = (int, Int)
|
|
102 |
|
|
103 |
type Board = List[List[Int]]
|
|
104 |
|
|
105 |
|
|
106 |
|
57
|
107 |
// Implicits
|
|
108 |
//===========
|
|
109 |
//
|
|
110 |
// for example adding your own methods to Strings:
|
|
111 |
// imagine you want to increment strings, like
|
|
112 |
//
|
|
113 |
// "HAL".increment
|
|
114 |
//
|
|
115 |
// you can avoid ugly fudges, like a MyString, by
|
|
116 |
// using implicit conversions
|
|
117 |
|
|
118 |
|
|
119 |
implicit class MyString(s: String) {
|
|
120 |
def increment = for (c <- s) yield (c + 1).toChar
|
|
121 |
}
|
|
122 |
|
|
123 |
"HAL".increment
|
|
124 |
|
|
125 |
|
53
|
126 |
// No return in Scala
|
|
127 |
//====================
|
|
128 |
|
|
129 |
//You should not use "return" in Scala:
|
|
130 |
//
|
|
131 |
// A return expression, when evaluated, abandons the
|
|
132 |
// current computation and returns to the caller of the
|
|
133 |
// function in which return appears."
|
|
134 |
|
|
135 |
def sq1(x: Int): Int = x * x
|
|
136 |
def sq2(x: Int): Int = return x * x
|
|
137 |
|
|
138 |
def sumq(ls: List[Int]): Int = {
|
|
139 |
(for (x <- ls) yield (return x * x)).sum[Int]
|
|
140 |
}
|
|
141 |
|
|
142 |
sumq(List(1,2,3,4))
|
36
|
143 |
|
57
|
144 |
|
53
|
145 |
// last expression in a function is the return statement
|
|
146 |
def square(x: Int): Int = {
|
|
147 |
println(s"The argument is ${x}.")
|
|
148 |
x * x
|
|
149 |
}
|
|
150 |
|
55
|
151 |
|
|
152 |
|
53
|
153 |
// Pattern Matching
|
|
154 |
//==================
|
|
155 |
|
|
156 |
// A powerful tool which is supposed to come to Java in a few years
|
|
157 |
// time (https://www.youtube.com/watch?v=oGll155-vuQ)...Scala already
|
|
158 |
// has it for many years ;o)
|
|
159 |
|
|
160 |
// The general schema:
|
|
161 |
//
|
|
162 |
// expression match {
|
|
163 |
// case pattern1 => expression1
|
|
164 |
// case pattern2 => expression2
|
|
165 |
// ...
|
|
166 |
// case patternN => expressionN
|
|
167 |
// }
|
|
168 |
|
|
169 |
|
|
170 |
// remember
|
|
171 |
val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
|
|
172 |
|
|
173 |
|
|
174 |
def my_flatten(xs: List[Option[Int]]): List[Int] = {
|
|
175 |
...
|
|
176 |
}
|
|
177 |
|
|
178 |
|
57
|
179 |
|
|
180 |
|
|
181 |
|
|
182 |
|
|
183 |
|
|
184 |
|
|
185 |
|
53
|
186 |
def my_flatten(lst: List[Option[Int]]): List[Int] = lst match {
|
|
187 |
case Nil => Nil
|
|
188 |
case None::xs => my_flatten(xs)
|
|
189 |
case Some(n)::xs => n::my_flatten(xs)
|
|
190 |
}
|
|
191 |
|
|
192 |
|
|
193 |
// another example
|
|
194 |
def get_me_a_string(n: Int): String = n match {
|
|
195 |
case 0 => "zero"
|
|
196 |
case 1 => "one"
|
|
197 |
case 2 => "two"
|
|
198 |
case _ => "many"
|
|
199 |
}
|
|
200 |
|
57
|
201 |
get_me_a_string(0)
|
|
202 |
|
55
|
203 |
// User-defined Datatypes
|
|
204 |
//========================
|
|
205 |
|
|
206 |
abstract class Tree
|
|
207 |
case class Node(elem: Int, left: Tree, right: Tree) extends Tree
|
|
208 |
case class Leaf() extends Tree
|
|
209 |
|
57
|
210 |
|
55
|
211 |
def insert(tr: Tree, n: Int): Tree = tr match {
|
|
212 |
case Leaf() => Node(n, Leaf(), Leaf())
|
|
213 |
case Node(m, left, right) =>
|
|
214 |
if (n == m) Node(m, left, right)
|
|
215 |
else if (n < m) Node(m, insert(left, n), right)
|
|
216 |
else Node(m, left, insert(right, n))
|
|
217 |
}
|
|
218 |
|
|
219 |
|
|
220 |
val t1 = Node(4, Node(2, Leaf(), Leaf()), Node(7, Leaf(), Leaf()))
|
|
221 |
insert(t1, 3)
|
|
222 |
|
61
|
223 |
def depth(tr: Tree): Int = tr match {
|
|
224 |
case Leaf() => 0
|
|
225 |
case Node(_, left, right) => 1 + List(depth(left), depth(right)).max
|
|
226 |
}
|
|
227 |
|
|
228 |
|
55
|
229 |
def balance(tr: Tree): Int = tr match {
|
|
230 |
case Leaf() => 0
|
61
|
231 |
case Node(_, left, right) => depth(left) - depth(right)
|
55
|
232 |
}
|
|
233 |
|
61
|
234 |
balance(insert(t1, 3))
|
55
|
235 |
|
|
236 |
// another example
|
|
237 |
|
|
238 |
abstract class Person
|
|
239 |
case class King() extends Person
|
|
240 |
case class Peer(deg: String, terr: String, succ: Int) extends Person
|
|
241 |
case class Knight(name: String) extends Person
|
|
242 |
case class Peasant(name: String) extends Person
|
|
243 |
case class Clown() extends Person
|
|
244 |
|
|
245 |
def title(p: Person): String = p match {
|
|
246 |
case King() => "His Majesty the King"
|
|
247 |
case Peer(deg, terr, _) => s"The ${deg} of ${terr}"
|
|
248 |
case Knight(name) => s"Sir ${name}"
|
|
249 |
case Peasant(name) => name
|
|
250 |
}
|
|
251 |
|
|
252 |
def superior(p1: Person, p2: Person): Boolean = (p1, p2) match {
|
|
253 |
case (King(), _) => true
|
|
254 |
case (Peer(_,_,_), Knight(_)) => true
|
|
255 |
case (Peer(_,_,_), Peasant(_)) => true
|
|
256 |
case (Peer(_,_,_), Clown()) => true
|
|
257 |
case (Knight(_), Peasant(_)) => true
|
|
258 |
case (Knight(_), Clown()) => true
|
|
259 |
case (Clown(), Peasant(_)) => true
|
|
260 |
case _ => false
|
|
261 |
}
|
|
262 |
|
|
263 |
val people = List(Knight("David"),
|
57
|
264 |
Peer("Duke", "Norfolk", 84),
|
55
|
265 |
Peasant("Christian"),
|
|
266 |
King(),
|
|
267 |
Clown())
|
|
268 |
|
57
|
269 |
println(people.sortWith(superior(_, _)).mkString(", "))
|
|
270 |
|
|
271 |
|
53
|
272 |
|
|
273 |
// Higher-Order Functions
|
|
274 |
//========================
|
|
275 |
|
|
276 |
// functions can take functions as arguments
|
|
277 |
|
|
278 |
val lst = (1 to 10).toList
|
|
279 |
|
|
280 |
def even(x: Int): Boolean = x % 2 == 0
|
|
281 |
def odd(x: Int): Boolean = x % 2 == 1
|
|
282 |
|
|
283 |
lst.filter(x => even(x))
|
|
284 |
lst.filter(even(_))
|
|
285 |
lst.filter(even)
|
|
286 |
|
|
287 |
lst.find(_ > 8)
|
|
288 |
|
|
289 |
def square(x: Int): Int = x * x
|
|
290 |
|
|
291 |
lst.map(square)
|
|
292 |
|
|
293 |
lst.map(square).filter(_ > 4)
|
|
294 |
|
55
|
295 |
lst.map(square).filter(_ > 4).map(square)
|
53
|
296 |
|
55
|
297 |
// in my collatz.scala
|
|
298 |
//(1 to bnd).map(i => (collatz(i), i)).maxBy(_._1)
|
|
299 |
|
|
300 |
|
57
|
301 |
// type of functions, for example f: Int => Int
|
|
302 |
|
55
|
303 |
def my_map_int(lst: List[Int], f: Int => Int): List[Int] = lst match {
|
|
304 |
case Nil => Nil
|
|
305 |
case x::xs => f(x)::my_map_int(xs, f)
|
|
306 |
}
|
|
307 |
|
|
308 |
my_map_int(lst, square)
|
|
309 |
|
57
|
310 |
// other function types
|
|
311 |
//
|
|
312 |
// f1: (Int, Int) => Int
|
|
313 |
// f2: List[String] => Option[Int]
|
|
314 |
// ...
|
|
315 |
|
55
|
316 |
|
|
317 |
def sumOf(f: Int => Int, lst: List[Int]): Int = lst match {
|
|
318 |
case Nil => 0
|
|
319 |
case x::xs => f(x) + sumOf(f, xs)
|
|
320 |
}
|
|
321 |
|
|
322 |
def sum_squares(lst: List[Int]) = sumOf(square, lst)
|
|
323 |
def sum_cubes(lst: List[Int]) = sumOf(x => x * x * x, lst)
|
|
324 |
|
|
325 |
sum_squares(lst)
|
|
326 |
sum_cubes(lst)
|
53
|
327 |
|
58
|
328 |
// lets try it factorial
|
|
329 |
def fact(n: Int): Int = ...
|
53
|
330 |
|
57
|
331 |
def sum_fact(lst: List[Int]) = sumOf(fact, lst)
|
|
332 |
sum_fact(lst)
|
56
|
333 |
|
|
334 |
// Avoid being mutable
|
|
335 |
//=====================
|
|
336 |
|
|
337 |
// a student showed me...
|
|
338 |
import scala.collection.mutable.ListBuffer
|
|
339 |
|
|
340 |
def collatz_max(bnd: Long): (Long, Long) = {
|
|
341 |
val colNos = ListBuffer[(Long, Long)]()
|
|
342 |
for (i <- (1L to bnd).toList) colNos += ((collatz(i), i))
|
|
343 |
colNos.max
|
|
344 |
}
|
|
345 |
|
|
346 |
def collatz_max(bnd: Long): (Long, Long) = {
|
|
347 |
(1L to bnd).map((i) => (collatz(i), i)).maxBy(_._1)
|
|
348 |
}
|
|
349 |
|
|
350 |
//views -> lazy collection
|
|
351 |
def collatz_max(bnd: Long): (Long, Long) = {
|
|
352 |
(1L to bnd).view.map((i) => (collatz(i), i)).maxBy(_._1)
|
|
353 |
}
|
|
354 |
|
|
355 |
// raises a GC exception
|
|
356 |
(1 to 1000000000).filter(_ % 2 == 0).take(10).toList
|
|
357 |
// ==> java.lang.OutOfMemoryError: GC overhead limit exceeded
|
|
358 |
|
|
359 |
(1 to 1000000000).view.filter(_ % 2 == 0).take(10).toList
|
|
360 |
|
57
|
361 |
|
|
362 |
|
53
|
363 |
// Sudoku
|
|
364 |
//========
|
|
365 |
|
57
|
366 |
// THE POINT OF THIS CODE IS NOT TO BE SUPER
|
|
367 |
// EFFICIENT AND FAST, just explaining exhaustive
|
|
368 |
// depth-first search
|
|
369 |
|
|
370 |
|
55
|
371 |
val game0 = """.14.6.3..
|
|
372 |
|62...4..9
|
|
373 |
|.8..5.6..
|
|
374 |
|.6.2....3
|
|
375 |
|.7..1..5.
|
|
376 |
|5....9.6.
|
|
377 |
|..6.2..3.
|
|
378 |
|1..5...92
|
|
379 |
|..7.9.41.""".stripMargin.replaceAll("\\n", "")
|
|
380 |
|
|
381 |
type Pos = (Int, Int)
|
|
382 |
val EmptyValue = '.'
|
|
383 |
val MaxValue = 9
|
|
384 |
|
|
385 |
val allValues = "123456789".toList
|
|
386 |
val indexes = (0 to 8).toList
|
|
387 |
|
57
|
388 |
|
|
389 |
|
55
|
390 |
|
57
|
391 |
def empty(game: String) = game.indexOf(EmptyValue)
|
|
392 |
def isDone(game: String) = empty(game) == -1
|
|
393 |
def emptyPosition(game: String) = (empty(game) % MaxValue, empty(game) / MaxValue)
|
|
394 |
|
55
|
395 |
|
57
|
396 |
def get_row(game: String, y: Int) = indexes.map(col => game(y * MaxValue + col))
|
|
397 |
def get_col(game: String, x: Int) = indexes.map(row => game(x + row * MaxValue))
|
|
398 |
|
|
399 |
def get_box(game: String, pos: Pos): List[Char] = {
|
55
|
400 |
def base(p: Int): Int = (p / 3) * 3
|
|
401 |
val x0 = base(pos._1)
|
|
402 |
val y0 = base(pos._2)
|
|
403 |
val ys = (y0 until y0 + 3).toList
|
|
404 |
(x0 until x0 + 3).toList.flatMap(x => ys.map(y => game(x + y * MaxValue)))
|
|
405 |
}
|
|
406 |
|
|
407 |
|
57
|
408 |
//get_row(game0, 0)
|
|
409 |
//get_row(game0, 1)
|
|
410 |
//get_box(game0, (3,1))
|
55
|
411 |
|
|
412 |
def update(game: String, pos: Int, value: Char): String = game.updated(pos, value)
|
|
413 |
|
|
414 |
def toAvoid(game: String, pos: Pos): List[Char] =
|
57
|
415 |
(get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos))
|
55
|
416 |
|
|
417 |
def candidates(game: String, pos: Pos): List[Char] = allValues diff toAvoid(game,pos)
|
|
418 |
|
|
419 |
//candidates(game0, (0,0))
|
|
420 |
|
|
421 |
def pretty(game: String): String = "\n" + (game sliding (MaxValue, MaxValue) mkString "\n")
|
|
422 |
|
|
423 |
def search(game: String): List[String] = {
|
|
424 |
if (isDone(game)) List(game)
|
|
425 |
else
|
57
|
426 |
candidates(game, emptyPosition(game)).map(c => search(update(game, empty(game), c))).toList.flatten
|
55
|
427 |
}
|
|
428 |
|
|
429 |
|
|
430 |
val game1 = """23.915...
|
|
431 |
|...2..54.
|
|
432 |
|6.7......
|
|
433 |
|..1.....9
|
|
434 |
|89.5.3.17
|
|
435 |
|5.....6..
|
|
436 |
|......9.5
|
|
437 |
|.16..7...
|
|
438 |
|...329..1""".stripMargin.replaceAll("\\n", "")
|
|
439 |
|
57
|
440 |
|
55
|
441 |
// game that is in the hard category
|
|
442 |
val game2 = """8........
|
|
443 |
|..36.....
|
|
444 |
|.7..9.2..
|
|
445 |
|.5...7...
|
|
446 |
|....457..
|
|
447 |
|...1...3.
|
|
448 |
|..1....68
|
|
449 |
|..85...1.
|
|
450 |
|.9....4..""".stripMargin.replaceAll("\\n", "")
|
|
451 |
|
|
452 |
// game with multiple solutions
|
|
453 |
val game3 = """.8...9743
|
|
454 |
|.5...8.1.
|
|
455 |
|.1.......
|
|
456 |
|8....5...
|
|
457 |
|...8.4...
|
|
458 |
|...3....6
|
|
459 |
|.......7.
|
|
460 |
|.3.5...8.
|
|
461 |
|9724...5.""".stripMargin.replaceAll("\\n", "")
|
|
462 |
|
57
|
463 |
|
55
|
464 |
search(game0).map(pretty)
|
|
465 |
search(game1).map(pretty)
|
|
466 |
|
|
467 |
// for measuring time
|
|
468 |
def time_needed[T](i: Int, code: => T) = {
|
|
469 |
val start = System.nanoTime()
|
|
470 |
for (j <- 1 to i) code
|
|
471 |
val end = System.nanoTime()
|
|
472 |
((end - start) / i / 1.0e9) + " secs"
|
|
473 |
}
|
|
474 |
|
|
475 |
search(game2).map(pretty)
|
57
|
476 |
search(game3).distinct.length
|
55
|
477 |
time_needed(3, search(game2))
|
|
478 |
time_needed(3, search(game3))
|
|
479 |
|
53
|
480 |
|
|
481 |
|
|
482 |
|
39
|
483 |
|