51
|
1 |
// Scala Lecture 2
|
|
2 |
//=================
|
|
3 |
|
204
|
4 |
|
|
5 |
|
316
|
6 |
// The Option Type
|
|
7 |
//=================
|
|
8 |
|
|
9 |
// in Java, if something unusually happens, you return null or
|
|
10 |
// raise an exception
|
|
11 |
//
|
|
12 |
//in Scala you use Options instead
|
|
13 |
// - if the value is present, you use Some(value)
|
|
14 |
// - if no value is present, you use None
|
204
|
15 |
|
|
16 |
|
316
|
17 |
List(7,2,3,4,5,6).find(_ < 4)
|
|
18 |
List(5,6,7,8,9).find(_ < 4)
|
212
|
19 |
|
310
|
20 |
|
|
21 |
|
316
|
22 |
// better error handling with Options (no exceptions)
|
|
23 |
//
|
|
24 |
// Try(something).getOrElse(what_to_do_in_case_of_an_exception)
|
204
|
25 |
//
|
316
|
26 |
|
|
27 |
import scala.util._
|
|
28 |
import io.Source
|
|
29 |
|
|
30 |
val my_url = "https://nms.kcl.ac.uk/christian.urban/"
|
|
31 |
|
|
32 |
Source.fromURL(my_url).mkString
|
|
33 |
|
|
34 |
Try(Source.fromURL(my_url).mkString).getOrElse("")
|
|
35 |
|
|
36 |
Try(Some(Source.fromURL(my_url).mkString)).getOrElse(None)
|
204
|
37 |
|
|
38 |
|
316
|
39 |
// the same for files
|
|
40 |
Try(Some(Source.fromFile("text.txt").mkString)).getOrElse(None)
|
|
41 |
|
|
42 |
// how to implement a function for reading something from files...
|
204
|
43 |
|
316
|
44 |
def get_contents(name: String) : List[String] =
|
|
45 |
Source.fromFile(name).getLines.toList
|
204
|
46 |
|
316
|
47 |
get_contents("test.txt")
|
204
|
48 |
|
316
|
49 |
// slightly better - return Nil
|
|
50 |
def get_contents(name: String) : List[String] =
|
|
51 |
Try(Source.fromFile(name).getLines.toList).getOrElse(List())
|
204
|
52 |
|
316
|
53 |
get_contents("text.txt")
|
204
|
54 |
|
316
|
55 |
// much better - you record in the type that things can go wrong
|
|
56 |
def get_contents(name: String) : Option[List[String]] =
|
|
57 |
Try(Some(Source.fromFile(name).getLines.toList)).getOrElse(None)
|
204
|
58 |
|
316
|
59 |
get_contents("text.txt")
|
|
60 |
get_contents("test.txt")
|
204
|
61 |
|
|
62 |
|
|
63 |
|
|
64 |
// For-Comprehensions Again
|
|
65 |
//==========================
|
|
66 |
|
|
67 |
// the first produces a result, while the second does not
|
|
68 |
for (n <- List(1, 2, 3, 4, 5)) yield n * n
|
|
69 |
|
|
70 |
|
|
71 |
for (n <- List(1, 2, 3, 4, 5)) println(n)
|
|
72 |
|
|
73 |
|
310
|
74 |
// String Interpolations
|
|
75 |
//=======================
|
|
76 |
|
|
77 |
val n = 3
|
|
78 |
println("The square of " + n + " is " + square(n) + ".")
|
|
79 |
|
|
80 |
println(s"The square of ${n} is ${square(n)}.")
|
|
81 |
|
|
82 |
|
|
83 |
// helpful for debugging purposes
|
|
84 |
//
|
|
85 |
// "The most effective debugging tool is still careful thought,
|
|
86 |
// coupled with judiciously placed print statements."
|
|
87 |
// — Brian W. Kernighan, in Unix for Beginners (1979)
|
|
88 |
|
|
89 |
|
|
90 |
def gcd_db(a: Int, b: Int) : Int = {
|
|
91 |
println(s"Function called with ${a} and ${b}.")
|
|
92 |
if (b == 0) a else gcd_db(b, a % b)
|
|
93 |
}
|
|
94 |
|
|
95 |
gcd_db(48, 18)
|
|
96 |
|
|
97 |
|
|
98 |
// Asserts/Testing
|
|
99 |
//=================
|
|
100 |
|
|
101 |
assert(gcd(48, 18) == 6)
|
|
102 |
|
|
103 |
assert(gcd(48, 18) == 5, "The gcd test failed")
|
|
104 |
|
|
105 |
|
204
|
106 |
|
|
107 |
// Higher-Order Functions
|
|
108 |
//========================
|
|
109 |
|
|
110 |
// functions can take functions as arguments
|
|
111 |
|
|
112 |
def even(x: Int) : Boolean = x % 2 == 0
|
|
113 |
def odd(x: Int) : Boolean = x % 2 == 1
|
|
114 |
|
|
115 |
val lst = (1 to 10).toList
|
|
116 |
|
|
117 |
lst.filter(x => even(x))
|
|
118 |
lst.filter(even(_))
|
|
119 |
lst.filter(even)
|
|
120 |
|
|
121 |
lst.count(even)
|
|
122 |
|
212
|
123 |
|
|
124 |
lst.find(even)
|
|
125 |
|
|
126 |
val ps = List((3, 0), (3, 2), (4, 2), (2, 2), (2, 0), (1, 1), (1, 0))
|
204
|
127 |
|
212
|
128 |
lst.sortWith(_ > _)
|
|
129 |
lst.sortWith(_ < _)
|
204
|
130 |
|
212
|
131 |
def lex(x: (Int, Int), y: (Int, Int)) : Boolean =
|
|
132 |
if (x._1 == y._1) x._2 < y._2 else x._1 < y._1
|
|
133 |
|
|
134 |
ps.sortWith(lex)
|
204
|
135 |
|
|
136 |
ps.sortBy(_._1)
|
|
137 |
ps.sortBy(_._2)
|
|
138 |
|
|
139 |
ps.maxBy(_._1)
|
|
140 |
ps.maxBy(_._2)
|
|
141 |
|
|
142 |
|
|
143 |
|
212
|
144 |
// maps (lower-case)
|
|
145 |
//===================
|
204
|
146 |
|
212
|
147 |
def double(x: Int): Int = x + x
|
204
|
148 |
def square(x: Int): Int = x * x
|
|
149 |
|
212
|
150 |
|
|
151 |
|
204
|
152 |
val lst = (1 to 10).toList
|
|
153 |
|
212
|
154 |
lst.map(x => (double(x), square(x)))
|
|
155 |
|
204
|
156 |
lst.map(square)
|
|
157 |
|
268
|
158 |
// this is actually how for-comprehensions
|
|
159 |
// defined as in Scala
|
204
|
160 |
|
|
161 |
lst.map(n => square(n))
|
|
162 |
for (n <- lst) yield square(n)
|
|
163 |
|
|
164 |
// this can be iterated
|
|
165 |
|
|
166 |
lst.map(square).filter(_ > 4)
|
|
167 |
|
|
168 |
lst.map(square).filter(_ > 4).map(square)
|
|
169 |
|
|
170 |
|
|
171 |
// lets define our own functions
|
|
172 |
// type of functions, for example f: Int => Int
|
|
173 |
|
212
|
174 |
lst.tail
|
|
175 |
|
204
|
176 |
def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = {
|
|
177 |
if (lst == Nil) Nil
|
|
178 |
else f(lst.head) :: my_map_int(lst.tail, f)
|
|
179 |
}
|
|
180 |
|
|
181 |
my_map_int(lst, square)
|
|
182 |
|
|
183 |
|
|
184 |
// same function using pattern matching: a kind
|
|
185 |
// of switch statement on steroids (see more later on)
|
|
186 |
|
|
187 |
def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = lst match {
|
|
188 |
case Nil => Nil
|
|
189 |
case x::xs => f(x)::my_map_int(xs, f)
|
|
190 |
}
|
|
191 |
|
|
192 |
|
|
193 |
// other function types
|
|
194 |
//
|
|
195 |
// f1: (Int, Int) => Int
|
|
196 |
// f2: List[String] => Option[Int]
|
|
197 |
// ...
|
212
|
198 |
val lst = (1 to 10).toList
|
204
|
199 |
|
|
200 |
def sumOf(f: Int => Int, lst: List[Int]): Int = lst match {
|
|
201 |
case Nil => 0
|
|
202 |
case x::xs => f(x) + sumOf(f, xs)
|
|
203 |
}
|
|
204 |
|
|
205 |
def sum_squares(lst: List[Int]) = sumOf(square, lst)
|
|
206 |
def sum_cubes(lst: List[Int]) = sumOf(x => x * x * x, lst)
|
|
207 |
|
|
208 |
sum_squares(lst)
|
|
209 |
sum_cubes(lst)
|
|
210 |
|
|
211 |
// lets try it factorial
|
212
|
212 |
def fact(n: Int) : Int =
|
|
213 |
if (n == 0) 1 else n * fact(n - 1)
|
204
|
214 |
|
|
215 |
def sum_fact(lst: List[Int]) = sumOf(fact, lst)
|
|
216 |
sum_fact(lst)
|
|
217 |
|
|
218 |
|
|
219 |
|
|
220 |
|
|
221 |
|
212
|
222 |
// Map type (upper-case)
|
|
223 |
//=======================
|
204
|
224 |
|
|
225 |
// Note the difference between map and Map
|
|
226 |
|
|
227 |
def factors(n: Int) : List[Int] =
|
|
228 |
((1 until n).filter { divisor =>
|
|
229 |
n % divisor == 0
|
|
230 |
}).toList
|
|
231 |
|
|
232 |
|
|
233 |
var ls = (1 to 10).toList
|
|
234 |
|
|
235 |
val facs = ls.map(n => (n, factors(n)))
|
|
236 |
|
|
237 |
facs.find(_._1 == 4)
|
|
238 |
|
|
239 |
// works for lists of pairs
|
|
240 |
facs.toMap
|
|
241 |
|
|
242 |
|
|
243 |
facs.toMap.get(4)
|
212
|
244 |
facs.toMap.getOrElse(42, Nil)
|
204
|
245 |
|
|
246 |
val facsMap = facs.toMap
|
|
247 |
|
|
248 |
val facsMap0 = facsMap + (0 -> List(1,2,3,4,5))
|
212
|
249 |
facsMap0.get(1)
|
204
|
250 |
|
|
251 |
val facsMap4 = facsMap + (1 -> List(1,2,3,4,5))
|
|
252 |
facsMap.get(1)
|
|
253 |
facsMap4.get(1)
|
|
254 |
|
|
255 |
val ls = List("one", "two", "three", "four", "five")
|
|
256 |
ls.groupBy(_.length)
|
|
257 |
|
212
|
258 |
ls.groupBy(_.length).get(2)
|
204
|
259 |
|
|
260 |
|
51
|
261 |
|
268
|
262 |
// Option type (again)
|
|
263 |
//=====================
|
53
|
264 |
|
268
|
265 |
// remember, in Java if something unusually happens,
|
|
266 |
// you return null;
|
204
|
267 |
//
|
268
|
268 |
// in Scala you use Option
|
53
|
269 |
// - if the value is present, you use Some(value)
|
|
270 |
// - if no value is present, you use None
|
|
271 |
|
|
272 |
|
192
|
273 |
List(7,2,3,4,5,6).find(_ < 4)
|
53
|
274 |
List(5,6,7,8,9).find(_ < 4)
|
|
275 |
|
204
|
276 |
// operations on options
|
58
|
277 |
|
51
|
278 |
val lst = List(None, Some(1), Some(2), None, Some(3))
|
|
279 |
|
|
280 |
lst.flatten
|
53
|
281 |
|
192
|
282 |
Some(1).get
|
212
|
283 |
None.get
|
51
|
284 |
|
53
|
285 |
Some(1).isDefined
|
|
286 |
None.isDefined
|
|
287 |
|
212
|
288 |
|
|
289 |
None.isDefined
|
|
290 |
|
51
|
291 |
val ps = List((3, 0), (3, 2), (4, 2), (2, 0), (1, 0), (1, 1))
|
|
292 |
|
|
293 |
for ((x, y) <- ps) yield {
|
|
294 |
if (y == 0) None else Some(x / y)
|
|
295 |
}
|
|
296 |
|
192
|
297 |
// getOrElse is for setting a default value
|
53
|
298 |
|
|
299 |
val lst = List(None, Some(1), Some(2), None, Some(3))
|
204
|
300 |
|
57
|
301 |
for (x <- lst) yield x.getOrElse(0)
|
|
302 |
|
|
303 |
|
53
|
304 |
|
|
305 |
|
192
|
306 |
// error handling with Option (no exceptions)
|
57
|
307 |
//
|
|
308 |
// Try(something).getOrElse(what_to_do_in_an_exception)
|
|
309 |
//
|
53
|
310 |
import scala.util._
|
|
311 |
import io.Source
|
|
312 |
|
212
|
313 |
|
|
314 |
Source.fromURL("""http://www.inf.ucl.ac.uk/staff/urbanc/""").mkString
|
53
|
315 |
|
192
|
316 |
Try(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString).getOrElse("")
|
53
|
317 |
|
192
|
318 |
Try(Some(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString)).getOrElse(None)
|
53
|
319 |
|
|
320 |
|
204
|
321 |
// a function that turns strings into numbers (similar to .toInt)
|
212
|
322 |
Integer.parseInt("12u34")
|
204
|
323 |
|
|
324 |
|
|
325 |
def get_me_an_int(s: String) : Option[Int] =
|
53
|
326 |
Try(Some(Integer.parseInt(s))).getOrElse(None)
|
|
327 |
|
204
|
328 |
val lst = List("12345", "foo", "5432", "bar", "x21", "456")
|
53
|
329 |
for (x <- lst) yield get_me_an_int(x)
|
|
330 |
|
268
|
331 |
// summing up all the numbers
|
204
|
332 |
|
212
|
333 |
lst.map(get_me_an_int).flatten.sum
|
204
|
334 |
lst.map(get_me_an_int).flatten.sum
|
|
335 |
|
|
336 |
|
212
|
337 |
lst.flatMap(get_me_an_int).map(_.toString)
|
53
|
338 |
|
|
339 |
|
|
340 |
// This may not look any better than working with null in Java, but to
|
|
341 |
// see the value, you have to put yourself in the shoes of the
|
|
342 |
// consumer of the get_me_an_int function, and imagine you didn't
|
|
343 |
// write that function.
|
|
344 |
//
|
|
345 |
// In Java, if you didn't write this function, you'd have to depend on
|
192
|
346 |
// the Javadoc of the get_me_an_int. If you didn't look at the Javadoc,
|
57
|
347 |
// you might not know that get_me_an_int could return a null, and your
|
|
348 |
// code could potentially throw a NullPointerException.
|
53
|
349 |
|
|
350 |
|
192
|
351 |
|
58
|
352 |
// even Scala is not immune to problems like this:
|
|
353 |
|
192
|
354 |
List(5,6,7,8,9).indexOf(7)
|
204
|
355 |
List(5,6,7,8,9).indexOf(10)
|
212
|
356 |
List(5,6,7,8,9)(-1)
|
192
|
357 |
|
|
358 |
|
|
359 |
|
|
360 |
// Pattern Matching
|
|
361 |
//==================
|
|
362 |
|
|
363 |
// A powerful tool which is supposed to come to Java in a few years
|
|
364 |
// time (https://www.youtube.com/watch?v=oGll155-vuQ)...Scala already
|
|
365 |
// has it for many years ;o)
|
|
366 |
|
|
367 |
// The general schema:
|
|
368 |
//
|
|
369 |
// expression match {
|
|
370 |
// case pattern1 => expression1
|
|
371 |
// case pattern2 => expression2
|
|
372 |
// ...
|
|
373 |
// case patternN => expressionN
|
|
374 |
// }
|
|
375 |
|
|
376 |
|
|
377 |
|
|
378 |
|
204
|
379 |
// remember?
|
192
|
380 |
val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
|
|
381 |
|
|
382 |
|
212
|
383 |
def my_flatten(xs: List[Option[Int]]): List[Int] = xs match {
|
|
384 |
case Nil => Nil
|
|
385 |
case None::rest => my_flatten(rest)
|
|
386 |
case Some(v)::foo => {
|
|
387 |
v :: my_flatten(foo)
|
|
388 |
}
|
192
|
389 |
}
|
58
|
390 |
|
|
391 |
|
192
|
392 |
// another example
|
|
393 |
def get_me_a_string(n: Int): String = n match {
|
212
|
394 |
case 0 | 1 | 2 => "small"
|
|
395 |
case _ => "big"
|
192
|
396 |
}
|
|
397 |
|
|
398 |
get_me_a_string(0)
|
|
399 |
|
212
|
400 |
|
192
|
401 |
// you can also have cases combined
|
266
|
402 |
def season(month: String) : String = month match {
|
192
|
403 |
case "March" | "April" | "May" => "It's spring"
|
|
404 |
case "June" | "July" | "August" => "It's summer"
|
|
405 |
case "September" | "October" | "November" => "It's autumn"
|
204
|
406 |
case "December" => "It's winter"
|
|
407 |
case "January" | "February" => "It's unfortunately winter"
|
192
|
408 |
}
|
|
409 |
|
|
410 |
println(season("November"))
|
|
411 |
|
|
412 |
// What happens if no case matches?
|
212
|
413 |
println(season("foobar"))
|
192
|
414 |
|
|
415 |
|
266
|
416 |
// Days of the months
|
|
417 |
def days(month: String) : Int = month match {
|
|
418 |
case "March" | "April" | "May" => 31
|
|
419 |
case "June" | "July" | "August" => 30
|
|
420 |
}
|
|
421 |
|
|
422 |
|
|
423 |
|
|
424 |
|
204
|
425 |
// Silly: fizz buzz
|
192
|
426 |
def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
|
|
427 |
case (0, 0) => "fizz buzz"
|
|
428 |
case (0, _) => "fizz"
|
|
429 |
case (_, 0) => "buzz"
|
|
430 |
case _ => n.toString
|
|
431 |
}
|
|
432 |
|
|
433 |
for (n <- 0 to 20)
|
|
434 |
println(fizz_buzz(n))
|
|
435 |
|
|
436 |
|
|
437 |
// User-defined Datatypes
|
|
438 |
//========================
|
|
439 |
|
|
440 |
|
204
|
441 |
abstract class Colour
|
|
442 |
case object Red extends Colour
|
|
443 |
case object Green extends Colour
|
|
444 |
case object Blue extends Colour
|
192
|
445 |
|
204
|
446 |
def fav_colour(c: Colour) : Boolean = c match {
|
|
447 |
case Red => false
|
|
448 |
case Green => true
|
|
449 |
case Blue => false
|
173
|
450 |
}
|
|
451 |
|
204
|
452 |
fav_colour(Green)
|
|
453 |
|
192
|
454 |
|
268
|
455 |
// ... a tiny bit more useful: Roman Numerals
|
204
|
456 |
|
|
457 |
abstract class RomanDigit
|
|
458 |
case object I extends RomanDigit
|
|
459 |
case object V extends RomanDigit
|
|
460 |
case object X extends RomanDigit
|
|
461 |
case object L extends RomanDigit
|
|
462 |
case object C extends RomanDigit
|
|
463 |
case object D extends RomanDigit
|
|
464 |
case object M extends RomanDigit
|
|
465 |
|
|
466 |
type RomanNumeral = List[RomanDigit]
|
192
|
467 |
|
212
|
468 |
List(X,I)
|
|
469 |
|
268
|
470 |
/*
|
212
|
471 |
I -> 1
|
|
472 |
II -> 2
|
|
473 |
III -> 3
|
|
474 |
IV -> 4
|
|
475 |
V -> 5
|
|
476 |
VI -> 6
|
|
477 |
VII -> 7
|
|
478 |
VIII -> 8
|
|
479 |
IX -> 9
|
|
480 |
X -> X
|
268
|
481 |
*/
|
212
|
482 |
|
204
|
483 |
def RomanNumeral2Int(rs: RomanNumeral): Int = rs match {
|
|
484 |
case Nil => 0
|
|
485 |
case M::r => 1000 + RomanNumeral2Int(r)
|
|
486 |
case C::M::r => 900 + RomanNumeral2Int(r)
|
|
487 |
case D::r => 500 + RomanNumeral2Int(r)
|
|
488 |
case C::D::r => 400 + RomanNumeral2Int(r)
|
|
489 |
case C::r => 100 + RomanNumeral2Int(r)
|
|
490 |
case X::C::r => 90 + RomanNumeral2Int(r)
|
|
491 |
case L::r => 50 + RomanNumeral2Int(r)
|
|
492 |
case X::L::r => 40 + RomanNumeral2Int(r)
|
|
493 |
case X::r => 10 + RomanNumeral2Int(r)
|
|
494 |
case I::X::r => 9 + RomanNumeral2Int(r)
|
|
495 |
case V::r => 5 + RomanNumeral2Int(r)
|
|
496 |
case I::V::r => 4 + RomanNumeral2Int(r)
|
|
497 |
case I::r => 1 + RomanNumeral2Int(r)
|
192
|
498 |
}
|
|
499 |
|
204
|
500 |
RomanNumeral2Int(List(I,V)) // 4
|
|
501 |
RomanNumeral2Int(List(I,I,I,I)) // 4 (invalid Roman number)
|
|
502 |
RomanNumeral2Int(List(V,I)) // 6
|
|
503 |
RomanNumeral2Int(List(I,X)) // 9
|
|
504 |
RomanNumeral2Int(List(M,C,M,L,X,X,I,X)) // 1979
|
|
505 |
RomanNumeral2Int(List(M,M,X,V,I,I)) // 2017
|
|
506 |
|
192
|
507 |
|
204
|
508 |
// another example
|
|
509 |
//=================
|
192
|
510 |
|
212
|
511 |
// Once upon a time, in a complete fictional
|
|
512 |
// country there were Persons...
|
192
|
513 |
|
|
514 |
|
|
515 |
abstract class Person
|
204
|
516 |
case object King extends Person
|
192
|
517 |
case class Peer(deg: String, terr: String, succ: Int) extends Person
|
|
518 |
case class Knight(name: String) extends Person
|
|
519 |
case class Peasant(name: String) extends Person
|
212
|
520 |
|
173
|
521 |
|
192
|
522 |
def title(p: Person): String = p match {
|
204
|
523 |
case King => "His Majesty the King"
|
192
|
524 |
case Peer(deg, terr, _) => s"The ${deg} of ${terr}"
|
|
525 |
case Knight(name) => s"Sir ${name}"
|
|
526 |
case Peasant(name) => name
|
|
527 |
}
|
173
|
528 |
|
192
|
529 |
def superior(p1: Person, p2: Person): Boolean = (p1, p2) match {
|
204
|
530 |
case (King, _) => true
|
192
|
531 |
case (Peer(_,_,_), Knight(_)) => true
|
|
532 |
case (Peer(_,_,_), Peasant(_)) => true
|
204
|
533 |
case (Peer(_,_,_), Clown) => true
|
192
|
534 |
case (Knight(_), Peasant(_)) => true
|
204
|
535 |
case (Knight(_), Clown) => true
|
|
536 |
case (Clown, Peasant(_)) => true
|
192
|
537 |
case _ => false
|
|
538 |
}
|
|
539 |
|
|
540 |
val people = List(Knight("David"),
|
|
541 |
Peer("Duke", "Norfolk", 84),
|
|
542 |
Peasant("Christian"),
|
204
|
543 |
King,
|
|
544 |
Clown)
|
192
|
545 |
|
212
|
546 |
println(people.sortWith(superior).mkString("\n"))
|
|
547 |
|
192
|
548 |
|
278
|
549 |
// String interpolations as patterns
|
|
550 |
|
|
551 |
val date = "2000-01-01"
|
|
552 |
val s"$year-$month-$day" = date
|
|
553 |
|
|
554 |
def parse_date(date: String) = date match {
|
|
555 |
case s"$year-$month-$day" => Some((year.toInt, month.toInt, day.toInt))
|
|
556 |
case s"$day/$month/$year" => Some((year.toInt, month.toInt, day.toInt))
|
|
557 |
case _ => None
|
|
558 |
}
|
|
559 |
|
|
560 |
|
309
|
561 |
// Recursion
|
|
562 |
//===========
|
|
563 |
|
|
564 |
/* a, b, c
|
|
565 |
|
|
566 |
aa aaa
|
|
567 |
ab baa
|
|
568 |
ac caa
|
|
569 |
ba => ......
|
|
570 |
bb
|
|
571 |
bc
|
|
572 |
ca
|
|
573 |
cb
|
|
574 |
cc
|
|
575 |
|
|
576 |
*/
|
|
577 |
|
|
578 |
def perms(cs: List[Char], l: Int) : List[String] = {
|
|
579 |
if (l == 0) List("")
|
|
580 |
else for (c <- cs; s <- perms(cs, l - 1)) yield s"$c$s"
|
|
581 |
}
|
|
582 |
|
|
583 |
perms("abc".toList, 2)
|
|
584 |
|
|
585 |
def move(from: Char, to: Char) =
|
|
586 |
println(s"Move disc from $from to $to!")
|
|
587 |
|
|
588 |
def hanoi(n: Int, from: Char, via: Char, to: Char) : Unit = {
|
|
589 |
if (n == 0) ()
|
|
590 |
else {
|
|
591 |
hanoi(n - 1, from, to, via)
|
|
592 |
move(from, to)
|
|
593 |
hanoi(n - 1, via, from, to)
|
|
594 |
}
|
|
595 |
}
|
|
596 |
|
|
597 |
hanoi(40, 'A', 'B', 'C')
|
|
598 |
|
|
599 |
|
268
|
600 |
// Tail Recursion
|
204
|
601 |
//================
|
147
|
602 |
|
|
603 |
|
204
|
604 |
def fact(n: Long): Long =
|
|
605 |
if (n == 0) 1 else n * fact(n - 1)
|
147
|
606 |
|
204
|
607 |
fact(10) //ok
|
|
608 |
fact(10000) // produces a stackoverflow
|
147
|
609 |
|
204
|
610 |
def factT(n: BigInt, acc: BigInt): BigInt =
|
|
611 |
if (n == 0) acc else factT(n - 1, n * acc)
|
147
|
612 |
|
204
|
613 |
factT(10, 1)
|
|
614 |
factT(100000, 1)
|
192
|
615 |
|
204
|
616 |
// there is a flag for ensuring a function is tail recursive
|
|
617 |
import scala.annotation.tailrec
|
167
|
618 |
|
204
|
619 |
@tailrec
|
|
620 |
def factT(n: BigInt, acc: BigInt): BigInt =
|
|
621 |
if (n == 0) acc else factT(n - 1, n * acc)
|
167
|
622 |
|
|
623 |
|
|
624 |
|
204
|
625 |
// for tail-recursive functions the Scala compiler
|
|
626 |
// generates loop-like code, which does not need
|
|
627 |
// to allocate stack-space in each recursive
|
|
628 |
// call; Scala can do this only for tail-recursive
|
|
629 |
// functions
|
|
630 |
|
147
|
631 |
|
212
|
632 |
// A Web Crawler / Email Harvester
|
|
633 |
//=================================
|
204
|
634 |
//
|
212
|
635 |
// the idea is to look for links using the
|
|
636 |
// regular expression "https?://[^"]*" and for
|
|
637 |
// email addresses using another regex.
|
204
|
638 |
|
|
639 |
import io.Source
|
|
640 |
import scala.util._
|
|
641 |
|
|
642 |
// gets the first 10K of a web-page
|
|
643 |
def get_page(url: String) : String = {
|
|
644 |
Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
|
|
645 |
getOrElse { println(s" Problem with: $url"); ""}
|
147
|
646 |
}
|
|
647 |
|
204
|
648 |
// regex for URLs and emails
|
|
649 |
val http_pattern = """"https?://[^"]*"""".r
|
|
650 |
val email_pattern = """([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})""".r
|
|
651 |
|
268
|
652 |
//test case:
|
212
|
653 |
//email_pattern.findAllIn
|
|
654 |
// ("foo bla christian@kcl.ac.uk 1234567").toList
|
|
655 |
|
204
|
656 |
|
|
657 |
// drops the first and last character from a string
|
|
658 |
def unquote(s: String) = s.drop(1).dropRight(1)
|
|
659 |
|
|
660 |
def get_all_URLs(page: String): Set[String] =
|
|
661 |
http_pattern.findAllIn(page).map(unquote).toSet
|
|
662 |
|
|
663 |
// naive version of crawl - searches until a given depth,
|
|
664 |
// visits pages potentially more than once
|
|
665 |
def crawl(url: String, n: Int) : Set[String] = {
|
|
666 |
if (n == 0) Set()
|
|
667 |
else {
|
|
668 |
println(s" Visiting: $n $url")
|
|
669 |
val page = get_page(url)
|
|
670 |
val new_emails = email_pattern.findAllIn(page).toSet
|
212
|
671 |
new_emails ++ (for (u <- get_all_URLs(page)) yield crawl(u, n - 1)).flatten
|
204
|
672 |
}
|
147
|
673 |
}
|
|
674 |
|
204
|
675 |
// some starting URLs for the crawler
|
|
676 |
val startURL = """https://nms.kcl.ac.uk/christian.urban/"""
|
147
|
677 |
|
204
|
678 |
crawl(startURL, 2)
|
|
679 |
|
|
680 |
|
|
681 |
|
|
682 |
|
150
|
683 |
|
|
684 |
|
|
685 |
|
192
|
686 |
// Sudoku
|
|
687 |
//========
|
53
|
688 |
|
57
|
689 |
// THE POINT OF THIS CODE IS NOT TO BE SUPER
|
|
690 |
// EFFICIENT AND FAST, just explaining exhaustive
|
|
691 |
// depth-first search
|
|
692 |
|
|
693 |
|
55
|
694 |
val game0 = """.14.6.3..
|
|
695 |
|62...4..9
|
|
696 |
|.8..5.6..
|
|
697 |
|.6.2....3
|
|
698 |
|.7..1..5.
|
|
699 |
|5....9.6.
|
|
700 |
|..6.2..3.
|
|
701 |
|1..5...92
|
|
702 |
|..7.9.41.""".stripMargin.replaceAll("\\n", "")
|
|
703 |
|
|
704 |
type Pos = (Int, Int)
|
268
|
705 |
val emptyValue = '.'
|
|
706 |
val maxValue = 9
|
55
|
707 |
|
|
708 |
val allValues = "123456789".toList
|
|
709 |
val indexes = (0 to 8).toList
|
|
710 |
|
57
|
711 |
|
268
|
712 |
def empty(game: String) = game.indexOf(emptyValue)
|
|
713 |
def isDone(game: String) = empty(game) == -1
|
|
714 |
def emptyPosition(game: String) : Pos =
|
|
715 |
(empty(game) % maxValue, empty(game) / maxValue)
|
57
|
716 |
|
55
|
717 |
|
268
|
718 |
def get_row(game: String, y: Int) = indexes.map(col => game(y * maxValue + col))
|
|
719 |
def get_col(game: String, x: Int) = indexes.map(row => game(x + row * maxValue))
|
147
|
720 |
|
57
|
721 |
def get_box(game: String, pos: Pos): List[Char] = {
|
55
|
722 |
def base(p: Int): Int = (p / 3) * 3
|
|
723 |
val x0 = base(pos._1)
|
|
724 |
val y0 = base(pos._2)
|
268
|
725 |
for (x <- (x0 until x0 + 3).toList;
|
|
726 |
y <- (y0 until y0 + 3).toList) yield game(x + y * maxValue)
|
|
727 |
}
|
55
|
728 |
|
|
729 |
|
192
|
730 |
//get_row(game0, 0)
|
|
731 |
//get_row(game0, 1)
|
|
732 |
//get_box(game0, (3,1))
|
|
733 |
|
268
|
734 |
def update(game: String, pos: Int, value: Char): String =
|
|
735 |
game.updated(pos, value)
|
55
|
736 |
|
|
737 |
def toAvoid(game: String, pos: Pos): List[Char] =
|
57
|
738 |
(get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos))
|
55
|
739 |
|
268
|
740 |
def candidates(game: String, pos: Pos): List[Char] =
|
|
741 |
allValues.diff(toAvoid(game, pos))
|
55
|
742 |
|
268
|
743 |
//candidates(game0, (0, 0))
|
55
|
744 |
|
268
|
745 |
def pretty(game: String): String =
|
|
746 |
"\n" ++ (game.sliding(maxValue, maxValue).mkString("\n"))
|
55
|
747 |
|
|
748 |
def search(game: String): List[String] = {
|
|
749 |
if (isDone(game)) List(game)
|
192
|
750 |
else
|
268
|
751 |
candidates(game, emptyPosition(game)).
|
|
752 |
map(c => search(update(game, empty(game), c))).flatten
|
55
|
753 |
}
|
|
754 |
|
268
|
755 |
// an easy game
|
55
|
756 |
val game1 = """23.915...
|
|
757 |
|...2..54.
|
|
758 |
|6.7......
|
|
759 |
|..1.....9
|
|
760 |
|89.5.3.17
|
|
761 |
|5.....6..
|
|
762 |
|......9.5
|
|
763 |
|.16..7...
|
|
764 |
|...329..1""".stripMargin.replaceAll("\\n", "")
|
|
765 |
|
57
|
766 |
|
268
|
767 |
// a game that is in the sligtly harder category
|
55
|
768 |
val game2 = """8........
|
|
769 |
|..36.....
|
|
770 |
|.7..9.2..
|
|
771 |
|.5...7...
|
|
772 |
|....457..
|
|
773 |
|...1...3.
|
|
774 |
|..1....68
|
|
775 |
|..85...1.
|
|
776 |
|.9....4..""".stripMargin.replaceAll("\\n", "")
|
|
777 |
|
268
|
778 |
// a game with multiple solutions
|
55
|
779 |
val game3 = """.8...9743
|
|
780 |
|.5...8.1.
|
|
781 |
|.1.......
|
|
782 |
|8....5...
|
|
783 |
|...8.4...
|
|
784 |
|...3....6
|
|
785 |
|.......7.
|
|
786 |
|.3.5...8.
|
|
787 |
|9724...5.""".stripMargin.replaceAll("\\n", "")
|
|
788 |
|
57
|
789 |
|
192
|
790 |
search(game0).map(pretty)
|
|
791 |
search(game1).map(pretty)
|
55
|
792 |
|
|
793 |
// for measuring time
|
|
794 |
def time_needed[T](i: Int, code: => T) = {
|
|
795 |
val start = System.nanoTime()
|
|
796 |
for (j <- 1 to i) code
|
|
797 |
val end = System.nanoTime()
|
268
|
798 |
s"${(end - start) / i / 1.0e9} secs"
|
55
|
799 |
}
|
|
800 |
|
|
801 |
search(game2).map(pretty)
|
57
|
802 |
search(game3).distinct.length
|
192
|
803 |
time_needed(3, search(game2))
|
|
804 |
time_needed(3, search(game3))
|
55
|
805 |
|
53
|
806 |
|
|
807 |
|
|
808 |
|
192
|
809 |
|
278
|
810 |
// if you like verbosity, you can full-specify the literal.
|
|
811 |
// Don't go telling that to people, though
|
|
812 |
(1 to 100).filter((x: Int) => x % 2 == 0).sum
|
|
813 |
|
|
814 |
// As x is known to be an Int anyway, you can omit that part
|
|
815 |
(1 to 100).filter(x => x % 2 == 0).sum
|
|
816 |
|
|
817 |
// As each parameter (only x in this case) is passed only once
|
|
818 |
// you can use the wizardy placeholder syntax
|
|
819 |
(1 to 100).filter(_ % 2 == 0).sum
|
|
820 |
|
|
821 |
// But if you want to re-use your literal, you can also put it in a value
|
|
822 |
// In this case, explicit types are required because there's nothing to infer from
|
|
823 |
val isEven: (x: Int) => x % 2 == 0
|
|
824 |
(1 to 100).filter(isEven).sum
|