|
51
|
1 |
// Scala Lecture 2
|
|
|
2 |
//=================
|
|
363
|
3 |
|
|
468
|
4 |
// - Options
|
|
|
5 |
// - Higher-Order Functions (short-hand notation)
|
|
|
6 |
// - maps (behind for-comprehensions)
|
|
|
7 |
// - Pattern-Matching
|
|
|
8 |
// - Recursion
|
|
361
|
9 |
|
|
504
|
10 |
|
|
|
11 |
// Function Definitions
|
|
|
12 |
//======================
|
|
|
13 |
|
|
|
14 |
// The general scheme for a function: you have to give a
|
|
|
15 |
// type to each argument and a return type of the function
|
|
|
16 |
//
|
|
|
17 |
// def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
|
|
|
18 |
// ....
|
|
|
19 |
// }
|
|
|
20 |
|
|
|
21 |
def incr(x: Int) : Int = x + 1
|
|
|
22 |
incr(42)
|
|
|
23 |
|
|
|
24 |
def add(x: Int, y: Int) : Int = x + y
|
|
|
25 |
|
|
|
26 |
|
|
|
27 |
def average(ls: List[Int]) : Option[Int] = {
|
|
|
28 |
val s = ls.sum
|
|
|
29 |
val l = ls.length
|
|
|
30 |
if (l == 0) None else Some(s / l)
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
average(List(1,2,3,4))
|
|
|
34 |
average(List())
|
|
|
35 |
|
|
|
36 |
|
|
|
37 |
|
|
|
38 |
|
|
316
|
39 |
// The Option Type
|
|
|
40 |
//=================
|
|
|
41 |
|
|
361
|
42 |
// in Java, if something unusually happens, you return null
|
|
|
43 |
// or raise an exception
|
|
316
|
44 |
//
|
|
|
45 |
//in Scala you use Options instead
|
|
|
46 |
// - if the value is present, you use Some(value)
|
|
|
47 |
// - if no value is present, you use None
|
|
204
|
48 |
|
|
|
49 |
|
|
316
|
50 |
List(7,2,3,4,5,6).find(_ < 4)
|
|
|
51 |
List(5,6,7,8,9).find(_ < 4)
|
|
212
|
52 |
|
|
361
|
53 |
// Int: ..., 0, 1, 2,...
|
|
|
54 |
// Boolean: true false
|
|
|
55 |
//
|
|
|
56 |
// List[Int]: Nil, List(_)
|
|
|
57 |
//
|
|
|
58 |
// Option[Int]: None, Some(0), Some(1), ...
|
|
444
|
59 |
// Option[Boolean]: None, Some(true), Some(false)
|
|
361
|
60 |
// Option[...]: None, Some(_)
|
|
|
61 |
|
|
491
|
62 |
def div(x: Int, y: Int) : Int =
|
|
|
63 |
x / y
|
|
|
64 |
|
|
361
|
65 |
def safe_div(x: Int, y: Int) : Option[Int] =
|
|
|
66 |
if (y == 0) None else Some(x / y)
|
|
|
67 |
|
|
491
|
68 |
def foo_calculation(x: Int) =
|
|
|
69 |
if (safe_div(x, x) == None) 24 else safe_div(x, x).get
|
|
|
70 |
|
|
|
71 |
foo_calculation(3)
|
|
|
72 |
foo_calculation(0)
|
|
|
73 |
|
|
|
74 |
safe_div(10 + 5, 3)
|
|
361
|
75 |
|
|
444
|
76 |
List(1,2,3,4,5,6).indexOf(7)
|
|
504
|
77 |
List[Int]().min
|
|
|
78 |
List[Int](1,2,3).minOption
|
|
444
|
79 |
|
|
361
|
80 |
|
|
310
|
81 |
|
|
316
|
82 |
// better error handling with Options (no exceptions)
|
|
|
83 |
//
|
|
|
84 |
// Try(something).getOrElse(what_to_do_in_case_of_an_exception)
|
|
204
|
85 |
//
|
|
316
|
86 |
|
|
468
|
87 |
import scala.util._ // Try,...
|
|
|
88 |
import io.Source // fromURL
|
|
316
|
89 |
|
|
504
|
90 |
//val my_url = "https://nms.kcl.ac.uk/christian.urban/"
|
|
|
91 |
val my_url = "https://urbanchr.github.io/"
|
|
|
92 |
|
|
|
93 |
println(Try(Source.fromURL(my_url)(using "ISO-8859-1").mkString).toOption)
|
|
316
|
94 |
|
|
504
|
95 |
.mkString
|
|
|
96 |
Source.fromURL(my_url)(using "ISO-8859-1").getLines().toList
|
|
316
|
97 |
|
|
504
|
98 |
Try(Source.fromURL(my_url)(using "ISO-8859-1").mkString).getOrElse("")
|
|
316
|
99 |
|
|
504
|
100 |
Try(Some(Source.fromURL(my_url)(using "ISO-8859-1").mkString)).getOrElse(None)
|
|
204
|
101 |
|
|
|
102 |
|
|
316
|
103 |
// the same for files
|
|
444
|
104 |
|
|
504
|
105 |
Try(Some(Source.fromFile("test.txt")(using "ISO-8859-1").mkString)).getOrElse(None)
|
|
316
|
106 |
|
|
504
|
107 |
Try(Source.fromFile("test.txt")(using "ISO-8859-1").mkString).toOption
|
|
444
|
108 |
|
|
504
|
109 |
Using(Source.fromFile("test.txt")(using "ISO-8859-1"))(_.mkString).toOption
|
|
204
|
110 |
|
|
319
|
111 |
// how to implement a function for reading
|
|
444
|
112 |
// (lines) from files...
|
|
319
|
113 |
//
|
|
316
|
114 |
def get_contents(name: String) : List[String] =
|
|
504
|
115 |
Source.fromFile(name)(using "ISO-8859-1").getLines().toList
|
|
204
|
116 |
|
|
319
|
117 |
get_contents("text.txt")
|
|
316
|
118 |
get_contents("test.txt")
|
|
204
|
119 |
|
|
316
|
120 |
// slightly better - return Nil
|
|
|
121 |
def get_contents(name: String) : List[String] =
|
|
504
|
122 |
Try(Source.fromFile(name)(using "ISO-8859-1").getLines.toList).getOrElse(List())
|
|
204
|
123 |
|
|
316
|
124 |
get_contents("text.txt")
|
|
204
|
125 |
|
|
316
|
126 |
// much better - you record in the type that things can go wrong
|
|
|
127 |
def get_contents(name: String) : Option[List[String]] =
|
|
504
|
128 |
Try(Some(Source.fromFile(name)(using "ISO-8859-1").getLines().toList)).getOrElse(None)
|
|
204
|
129 |
|
|
316
|
130 |
get_contents("text.txt")
|
|
|
131 |
get_contents("test.txt")
|
|
204
|
132 |
|
|
|
133 |
|
|
317
|
134 |
// operations on options
|
|
204
|
135 |
|
|
317
|
136 |
val lst = List(None, Some(1), Some(2), None, Some(3))
|
|
204
|
137 |
|
|
491
|
138 |
for (x <- lst) yield {
|
|
|
139 |
if (x == None) None
|
|
|
140 |
else Some(x.get + 1)
|
|
|
141 |
}
|
|
|
142 |
|
|
317
|
143 |
lst.flatten
|
|
204
|
144 |
|
|
317
|
145 |
Some(1).get
|
|
|
146 |
None.get
|
|
310
|
147 |
|
|
317
|
148 |
Some(1).isDefined
|
|
|
149 |
None.isDefined
|
|
310
|
150 |
|
|
361
|
151 |
for (x <- lst) yield x.getOrElse(0)
|
|
310
|
152 |
|
|
361
|
153 |
|
|
|
154 |
|
|
|
155 |
val ps = List((3, 0), (4, 2), (6, 2),
|
|
|
156 |
(2, 0), (1, 0), (1, 1))
|
|
317
|
157 |
|
|
|
158 |
// division where possible
|
|
|
159 |
|
|
|
160 |
for ((x, y) <- ps) yield {
|
|
|
161 |
if (y == 0) None else Some(x / y)
|
|
|
162 |
}
|
|
|
163 |
|
|
361
|
164 |
|
|
|
165 |
|
|
317
|
166 |
// getOrElse is for setting a default value
|
|
|
167 |
|
|
|
168 |
val lst = List(None, Some(1), Some(2), None, Some(3))
|
|
|
169 |
|
|
361
|
170 |
|
|
|
171 |
// a function that turns strings into numbers
|
|
|
172 |
// (similar to .toInt)
|
|
|
173 |
Integer.parseInt("1234")
|
|
318
|
174 |
|
|
|
175 |
|
|
|
176 |
def get_me_an_int(s: String) : Option[Int] =
|
|
|
177 |
Try(Some(Integer.parseInt(s))).getOrElse(None)
|
|
310
|
178 |
|
|
|
179 |
|
|
317
|
180 |
// This may not look any better than working with null in Java, but to
|
|
|
181 |
// see the value, you have to put yourself in the shoes of the
|
|
|
182 |
// consumer of the get_me_an_int function, and imagine you didn't
|
|
|
183 |
// write that function.
|
|
|
184 |
//
|
|
|
185 |
// In Java, if you didn't write this function, you'd have to depend on
|
|
|
186 |
// the Javadoc of the get_me_an_int. If you didn't look at the Javadoc,
|
|
318
|
187 |
// you might not know that get_me_an_int could return null, and your
|
|
317
|
188 |
// code could potentially throw a NullPointerException.
|
|
310
|
189 |
|
|
|
190 |
|
|
317
|
191 |
// even Scala is not immune to problems like this:
|
|
310
|
192 |
|
|
317
|
193 |
List(5,6,7,8,9).indexOf(7)
|
|
|
194 |
List(5,6,7,8,9).indexOf(10)
|
|
|
195 |
List(5,6,7,8,9)(-1)
|
|
310
|
196 |
|
|
|
197 |
|
|
320
|
198 |
Try({
|
|
|
199 |
val x = 3
|
|
|
200 |
val y = 0
|
|
|
201 |
Some(x / y)
|
|
|
202 |
}).getOrElse(None)
|
|
204
|
203 |
|
|
323
|
204 |
|
|
|
205 |
// minOption
|
|
|
206 |
// maxOption
|
|
|
207 |
// minByOption
|
|
|
208 |
// maxByOption
|
|
|
209 |
|
|
504
|
210 |
def altproduct(xs: List[Int]) : List[Int] = xs match {
|
|
|
211 |
case Nil => Nil
|
|
|
212 |
case (x::y::xs) => x * y :: altproduct(y::xs)
|
|
|
213 |
case (x::Nil) => List(x)
|
|
|
214 |
}
|
|
|
215 |
|
|
|
216 |
altproduct(List(1,2,3,4,5))
|
|
|
217 |
|
|
|
218 |
def powerset(xs: Set[Int]) : Set[Set[Int]] = {
|
|
|
219 |
if (xs == Set()) Set(Set())
|
|
|
220 |
else {
|
|
|
221 |
powerset(xs.tail) ++ powerset(xs.tail).map(_ + xs.head)
|
|
|
222 |
}
|
|
|
223 |
}
|
|
|
224 |
|
|
|
225 |
powerset(Set(1,2,3)).mkString("\n")
|
|
|
226 |
|
|
204
|
227 |
// Higher-Order Functions
|
|
|
228 |
//========================
|
|
|
229 |
|
|
|
230 |
// functions can take functions as arguments
|
|
319
|
231 |
// and produce functions as result
|
|
204
|
232 |
|
|
504
|
233 |
val foo = for (n <- (1 to 10).toList) yield n * n
|
|
|
234 |
|
|
|
235 |
|
|
204
|
236 |
def even(x: Int) : Boolean = x % 2 == 0
|
|
504
|
237 |
|
|
|
238 |
even(2)
|
|
|
239 |
even(3)
|
|
|
240 |
|
|
|
241 |
def even(x: Int) : Boolean = x % 2 == 1
|
|
|
242 |
|
|
|
243 |
val foo_fun = even
|
|
|
244 |
|
|
|
245 |
foo_fun(2)
|
|
|
246 |
foo_fun(3)
|
|
|
247 |
|
|
|
248 |
|
|
204
|
249 |
def odd(x: Int) : Boolean = x % 2 == 1
|
|
|
250 |
|
|
478
|
251 |
def inc(x: Int) : Int = x + 1
|
|
204
|
252 |
val lst = (1 to 10).toList
|
|
|
253 |
|
|
491
|
254 |
lst.filter(odd)
|
|
504
|
255 |
lst.find(even)
|
|
|
256 |
lst.find(_ % 2 == 0)
|
|
|
257 |
lst.sortWith(_ < _) // (x,y) => x < y
|
|
|
258 |
lst.find(_ > 4)
|
|
320
|
259 |
lst.count(odd)
|
|
491
|
260 |
|
|
|
261 |
lst.filter(_ % 2 == 0)
|
|
|
262 |
|
|
|
263 |
|
|
212
|
264 |
|
|
362
|
265 |
lst.find(_ < 4)
|
|
320
|
266 |
lst.filter(_ < 4)
|
|
362
|
267 |
|
|
478
|
268 |
val x = 3 < 4
|
|
|
269 |
|
|
362
|
270 |
def less4(x: Int) : Boolean = x < 4
|
|
|
271 |
lst.find(less4)
|
|
478
|
272 |
lst.find(x => !(x < 4))
|
|
362
|
273 |
|
|
|
274 |
lst.filter(x => x % 2 == 0)
|
|
318
|
275 |
lst.filter(_ % 2 == 0)
|
|
204
|
276 |
|
|
320
|
277 |
|
|
491
|
278 |
lst.sortWith((x, y) => x > y)
|
|
|
279 |
lst.sortWith(_ < _)
|
|
204
|
280 |
|
|
318
|
281 |
// but this only works when the arguments are clear, but
|
|
|
282 |
// not with multiple occurences
|
|
|
283 |
lst.find(n => odd(n) && n > 2)
|
|
|
284 |
|
|
|
285 |
|
|
444
|
286 |
// lexicographic ordering
|
|
362
|
287 |
val ps = List((3, 0), (3, 2), (4, 2), (2, 2),
|
|
|
288 |
(2, 0), (1, 1), (1, 0))
|
|
318
|
289 |
|
|
212
|
290 |
def lex(x: (Int, Int), y: (Int, Int)) : Boolean =
|
|
|
291 |
if (x._1 == y._1) x._2 < y._2 else x._1 < y._1
|
|
|
292 |
|
|
|
293 |
ps.sortWith(lex)
|
|
204
|
294 |
|
|
320
|
295 |
ps.sortBy(x => x._1)
|
|
204
|
296 |
ps.sortBy(_._2)
|
|
|
297 |
|
|
491
|
298 |
ps.maxBy(x => x._2)
|
|
204
|
299 |
ps.maxBy(_._2)
|
|
|
300 |
|
|
|
301 |
|
|
212
|
302 |
// maps (lower-case)
|
|
|
303 |
//===================
|
|
204
|
304 |
|
|
212
|
305 |
def double(x: Int): Int = x + x
|
|
204
|
306 |
def square(x: Int): Int = x * x
|
|
|
307 |
|
|
|
308 |
val lst = (1 to 10).toList
|
|
|
309 |
|
|
362
|
310 |
lst.map(square)
|
|
491
|
311 |
lst.map(n => square(n))
|
|
|
312 |
|
|
|
313 |
for (n <- lst) yield square(n)
|
|
|
314 |
|
|
212
|
315 |
lst.map(x => (double(x), square(x)))
|
|
|
316 |
|
|
362
|
317 |
// works also for strings
|
|
|
318 |
def tweet(c: Char) = c.toUpper
|
|
|
319 |
|
|
478
|
320 |
"Hello\nWorld".map(tweet)
|
|
362
|
321 |
|
|
|
322 |
|
|
|
323 |
// this can be iterated
|
|
|
324 |
|
|
|
325 |
lst.map(square).filter(_ > 4)
|
|
|
326 |
|
|
363
|
327 |
lst.map(square).find(_ > 4)
|
|
|
328 |
lst.map(square).find(_ > 4).map(double)
|
|
|
329 |
|
|
|
330 |
lst.map(square)
|
|
362
|
331 |
.find(_ > 4)
|
|
363
|
332 |
.map(double)
|
|
|
333 |
|
|
|
334 |
|
|
|
335 |
// Option Type and maps
|
|
|
336 |
//======================
|
|
|
337 |
|
|
|
338 |
// a function that turns strings into numbers (similar to .toInt)
|
|
|
339 |
Integer.parseInt("12u34")
|
|
|
340 |
|
|
|
341 |
// maps on Options
|
|
|
342 |
|
|
|
343 |
import scala.util._
|
|
362
|
344 |
|
|
363
|
345 |
def get_me_an_int(s: String) : Option[Int] =
|
|
|
346 |
Try(Some(Integer.parseInt(s))).getOrElse(None)
|
|
|
347 |
|
|
|
348 |
get_me_an_int("12345").map(_ % 2 == 0)
|
|
|
349 |
get_me_an_int("12u34").map(_ % 2 == 0)
|
|
|
350 |
|
|
|
351 |
|
|
|
352 |
|
|
|
353 |
val lst = List("12345", "foo", "5432", "bar", "x21", "456")
|
|
|
354 |
for (x <- lst) yield get_me_an_int(x)
|
|
|
355 |
|
|
|
356 |
// summing up all the numbers
|
|
|
357 |
|
|
|
358 |
lst.map(get_me_an_int).flatten.sum
|
|
|
359 |
|
|
|
360 |
|
|
|
361 |
|
|
204
|
362 |
|
|
319
|
363 |
// this is actually how for-comprehensions are
|
|
|
364 |
// defined in Scala
|
|
204
|
365 |
|
|
|
366 |
lst.map(n => square(n))
|
|
|
367 |
for (n <- lst) yield square(n)
|
|
|
368 |
|
|
318
|
369 |
// lets define our own higher-order functions
|
|
|
370 |
// type of functions is for example Int => Int
|
|
204
|
371 |
|
|
212
|
372 |
|
|
363
|
373 |
def my_map_int(lst: List[Int], f: Int => Int) : List[Int] =
|
|
|
374 |
{
|
|
204
|
375 |
if (lst == Nil) Nil
|
|
|
376 |
else f(lst.head) :: my_map_int(lst.tail, f)
|
|
|
377 |
}
|
|
|
378 |
|
|
|
379 |
my_map_int(lst, square)
|
|
|
380 |
|
|
|
381 |
// same function using pattern matching: a kind
|
|
|
382 |
// of switch statement on steroids (see more later on)
|
|
|
383 |
|
|
319
|
384 |
def my_map_int(lst: List[Int], f: Int => Int) : List[Int] =
|
|
362
|
385 |
lst match {
|
|
|
386 |
case Nil => Nil
|
|
|
387 |
case x::xs => f(x)::my_map_int(xs, f)
|
|
|
388 |
}
|
|
204
|
389 |
|
|
|
390 |
|
|
363
|
391 |
|
|
|
392 |
val biglst = (1 to 10000).toList
|
|
|
393 |
my_map_int(biglst, double)
|
|
|
394 |
|
|
|
395 |
(1 to 10000000).toList.map(double)
|
|
|
396 |
|
|
204
|
397 |
// other function types
|
|
|
398 |
//
|
|
|
399 |
// f1: (Int, Int) => Int
|
|
|
400 |
// f2: List[String] => Option[Int]
|
|
|
401 |
// ...
|
|
|
402 |
|
|
|
403 |
|
|
320
|
404 |
|
|
204
|
405 |
|
|
|
406 |
|
|
212
|
407 |
// Map type (upper-case)
|
|
|
408 |
//=======================
|
|
204
|
409 |
|
|
|
410 |
// Note the difference between map and Map
|
|
|
411 |
|
|
364
|
412 |
val m = Map(1 -> "one", 2 -> "two", 10 -> "many")
|
|
320
|
413 |
|
|
364
|
414 |
List((1, "one"), (2, "two"), (10, "many")).toMap
|
|
320
|
415 |
|
|
364
|
416 |
m.get(1)
|
|
|
417 |
m.get(4)
|
|
204
|
418 |
|
|
364
|
419 |
m.getOrElse(1, "")
|
|
|
420 |
m.getOrElse(4, "")
|
|
204
|
421 |
|
|
364
|
422 |
val new_m = m + (10 -> "ten")
|
|
204
|
423 |
|
|
364
|
424 |
new_m.get(10)
|
|
|
425 |
|
|
|
426 |
val m2 = for ((k, v) <- m) yield (k, v.toUpperCase)
|
|
204
|
427 |
|
|
|
428 |
|
|
318
|
429 |
|
|
319
|
430 |
// groupBy function on Maps
|
|
364
|
431 |
val lst = List("one", "two", "three", "four", "five")
|
|
|
432 |
lst.groupBy(_.head)
|
|
204
|
433 |
|
|
364
|
434 |
lst.groupBy(_.length)
|
|
204
|
435 |
|
|
364
|
436 |
lst.groupBy(_.length).get(3)
|
|
|
437 |
|
|
|
438 |
val grps = lst.groupBy(_.length)
|
|
|
439 |
grps.keySet
|
|
204
|
440 |
|
|
478
|
441 |
// naive quicksort with "On" function
|
|
|
442 |
|
|
|
443 |
def sortOn(f: Int => Int, xs: List[Int]) : List[Int] = {
|
|
|
444 |
if (xs.size < 2) xs
|
|
|
445 |
else {
|
|
|
446 |
val pivot = xs.head
|
|
|
447 |
val (left, right) = xs.partition(f(_) < f(pivot))
|
|
|
448 |
sortOn(f, left) ::: pivot :: sortOn(f, right.tail)
|
|
|
449 |
}
|
|
|
450 |
}
|
|
|
451 |
|
|
|
452 |
sortOn(identity, List(99,99,99,98,10,-3,2))
|
|
|
453 |
sortOn(n => - n, List(99,99,99,98,10,-3,2))
|
|
204
|
454 |
|
|
51
|
455 |
|
|
192
|
456 |
|
|
|
457 |
// Pattern Matching
|
|
|
458 |
//==================
|
|
|
459 |
|
|
468
|
460 |
// A powerful tool which has even landed in Java during
|
|
|
461 |
// the last few years (https://inside.java/2021/06/13/podcast-017/).
|
|
|
462 |
// ...Scala already has it for many years and the concept is
|
|
|
463 |
// older than your friendly lecturer, that is stone old ;o)
|
|
192
|
464 |
|
|
|
465 |
// The general schema:
|
|
|
466 |
//
|
|
|
467 |
// expression match {
|
|
|
468 |
// case pattern1 => expression1
|
|
|
469 |
// case pattern2 => expression2
|
|
|
470 |
// ...
|
|
|
471 |
// case patternN => expressionN
|
|
|
472 |
// }
|
|
|
473 |
|
|
|
474 |
|
|
319
|
475 |
// recall
|
|
365
|
476 |
def my_map_int(lst: List[Int], f: Int => Int) : List[Int] =
|
|
|
477 |
lst match {
|
|
|
478 |
case Nil => Nil
|
|
|
479 |
case x::xs => f(x)::my_map_int(xs, f)
|
|
|
480 |
}
|
|
58
|
481 |
|
|
468
|
482 |
def my_map_option(opt: Option[Int], f: Int => Int) : Option[Int] =
|
|
|
483 |
opt match {
|
|
365
|
484 |
case None => None
|
|
|
485 |
case Some(x) => Some(f(x))
|
|
|
486 |
}
|
|
58
|
487 |
|
|
365
|
488 |
my_map_option(None, x => x * x)
|
|
|
489 |
my_map_option(Some(8), x => x * x)
|
|
192
|
490 |
|
|
212
|
491 |
|
|
192
|
492 |
// you can also have cases combined
|
|
266
|
493 |
def season(month: String) : String = month match {
|
|
192
|
494 |
case "March" | "April" | "May" => "It's spring"
|
|
|
495 |
case "June" | "July" | "August" => "It's summer"
|
|
|
496 |
case "September" | "October" | "November" => "It's autumn"
|
|
204
|
497 |
case "December" => "It's winter"
|
|
|
498 |
case "January" | "February" => "It's unfortunately winter"
|
|
365
|
499 |
case _ => "Wrong month"
|
|
266
|
500 |
}
|
|
|
501 |
|
|
365
|
502 |
// pattern-match on integers
|
|
|
503 |
|
|
|
504 |
def fib(n: Int) : Int = n match {
|
|
|
505 |
case 0 | 1 => 1
|
|
|
506 |
case n => fib(n - 1) + fib(n - 2)
|
|
|
507 |
}
|
|
|
508 |
|
|
|
509 |
fib(10)
|
|
266
|
510 |
|
|
204
|
511 |
// Silly: fizz buzz
|
|
192
|
512 |
def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
|
|
|
513 |
case (0, 0) => "fizz buzz"
|
|
|
514 |
case (0, _) => "fizz"
|
|
|
515 |
case (_, 0) => "buzz"
|
|
|
516 |
case _ => n.toString
|
|
|
517 |
}
|
|
|
518 |
|
|
365
|
519 |
for (n <- 1 to 20)
|
|
192
|
520 |
println(fizz_buzz(n))
|
|
|
521 |
|
|
|
522 |
|
|
365
|
523 |
val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
|
|
|
524 |
|
|
|
525 |
def my_flatten(xs: List[Option[Int]]): List[Int] =
|
|
|
526 |
xs match {
|
|
|
527 |
case Nil => Nil
|
|
|
528 |
case None::rest => my_flatten(rest)
|
|
|
529 |
case Some(v)::rest => v :: my_flatten(rest)
|
|
|
530 |
}
|
|
|
531 |
|
|
|
532 |
my_flatten(List(None, Some(1), Some(2), None, Some(3)))
|
|
|
533 |
|
|
|
534 |
|
|
|
535 |
|
|
504
|
536 |
|
|
|
537 |
// Recursion
|
|
|
538 |
//===========
|
|
|
539 |
|
|
|
540 |
// my_length
|
|
|
541 |
|
|
|
542 |
def my_length(xs: List[Int]) : Int = {
|
|
|
543 |
if (xs == Nil) 0 else 1 + my_length(xs.tail)
|
|
|
544 |
}
|
|
|
545 |
|
|
|
546 |
def my_sum(xs: List[Int]) : Int = {
|
|
|
547 |
if (xs == Nil) 0 else xs.head + my_sum(xs.tail)
|
|
|
548 |
}
|
|
|
549 |
|
|
|
550 |
my_sum((1 to 100).toList)
|
|
|
551 |
my_length(List())
|
|
|
552 |
|
|
|
553 |
/* my_map */
|
|
|
554 |
for (n <- List[Int](1,2,3)) yield n * n
|
|
|
555 |
|
|
|
556 |
List(1,2,3) ::: List(3,4,5)
|
|
|
557 |
3 :: List(3,4,5)
|
|
|
558 |
|
|
|
559 |
def my_map(xs: List[Int], f : Int => Int ) : List[Int] = {
|
|
|
560 |
if (xs == Nil) Nil
|
|
|
561 |
else f(xs.head) :: my_map(xs.tail, f)
|
|
|
562 |
}
|
|
|
563 |
|
|
|
564 |
def square(n: Int) : Int = n * n
|
|
|
565 |
|
|
|
566 |
|
|
|
567 |
my_map(List(1,2,3), square)
|
|
365
|
568 |
|
|
|
569 |
|
|
278
|
570 |
|
|
|
571 |
|
|
504
|
572 |
/* powerset */
|
|
|
573 |
|
|
|
574 |
def powerset(xs: Set[Int]) : Set[Set[Int]] = {
|
|
|
575 |
if (xs == Set()) Set(Set())
|
|
|
576 |
else powerset(xs.tail) ++ powerset(xs.tail).map(_ + xs.head)
|
|
|
577 |
}
|
|
|
578 |
|
|
|
579 |
|
|
|
580 |
|
|
|
581 |
|
|
|
582 |
|
|
|
583 |
/* on lists */
|
|
|
584 |
def powerset(xs: List[Int]) : List[List[Int]] = {
|
|
|
585 |
if (xs == Nil) List(Nil)
|
|
|
586 |
else powerset(xs.tail) ::: powerset(xs.tail).map(xs.head :: _)
|
|
|
587 |
}
|
|
|
588 |
|
|
309
|
589 |
|
|
|
590 |
|
|
318
|
591 |
/* Say you have characters a, b, c.
|
|
|
592 |
What are all the combinations of a certain length?
|
|
309
|
593 |
|
|
318
|
594 |
All combinations of length 2:
|
|
|
595 |
|
|
|
596 |
aa, ab, ac, ba, bb, bc, ca, cb, cc
|
|
|
597 |
|
|
|
598 |
Combinations of length 3:
|
|
|
599 |
|
|
|
600 |
aaa, baa, caa, and so on......
|
|
309
|
601 |
*/
|
|
|
602 |
|
|
320
|
603 |
def combs(cs: List[Char], n: Int) : List[String] = {
|
|
|
604 |
if (n == 0) List("")
|
|
|
605 |
else for (c <- cs; s <- combs(cs, n - 1)) yield s"$c$s"
|
|
|
606 |
}
|
|
|
607 |
|
|
|
608 |
combs(List('a', 'b', 'c'), 3)
|
|
|
609 |
|
|
|
610 |
|
|
|
611 |
|
|
318
|
612 |
def combs(cs: List[Char], l: Int) : List[String] = {
|
|
309
|
613 |
if (l == 0) List("")
|
|
318
|
614 |
else for (c <- cs; s <- combs(cs, l - 1)) yield s"$c$s"
|
|
309
|
615 |
}
|
|
|
616 |
|
|
318
|
617 |
combs("abc".toList, 2)
|
|
|
618 |
|
|
|
619 |
|
|
329
|
620 |
// When writing recursive functions you have to
|
|
|
621 |
// think about three points
|
|
|
622 |
//
|
|
|
623 |
// - How to start with a recursive function
|
|
|
624 |
// - How to communicate between recursive calls
|
|
|
625 |
// - Exit conditions
|
|
|
626 |
|
|
|
627 |
|
|
147
|
628 |
|
|
318
|
629 |
// A Recursive Web Crawler / Email Harvester
|
|
|
630 |
//===========================================
|
|
204
|
631 |
//
|
|
212
|
632 |
// the idea is to look for links using the
|
|
|
633 |
// regular expression "https?://[^"]*" and for
|
|
|
634 |
// email addresses using another regex.
|
|
204
|
635 |
|
|
|
636 |
import io.Source
|
|
|
637 |
import scala.util._
|
|
|
638 |
|
|
|
639 |
// gets the first 10K of a web-page
|
|
|
640 |
def get_page(url: String) : String = {
|
|
504
|
641 |
Try(Source.fromURL(url)(using "ISO-8859-1").take(10000).mkString).
|
|
204
|
642 |
getOrElse { println(s" Problem with: $url"); ""}
|
|
147
|
643 |
}
|
|
|
644 |
|
|
204
|
645 |
// regex for URLs and emails
|
|
|
646 |
val http_pattern = """"https?://[^"]*"""".r
|
|
|
647 |
val email_pattern = """([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})""".r
|
|
|
648 |
|
|
268
|
649 |
//test case:
|
|
212
|
650 |
//email_pattern.findAllIn
|
|
|
651 |
// ("foo bla christian@kcl.ac.uk 1234567").toList
|
|
|
652 |
|
|
204
|
653 |
|
|
|
654 |
// drops the first and last character from a string
|
|
|
655 |
def unquote(s: String) = s.drop(1).dropRight(1)
|
|
|
656 |
|
|
|
657 |
def get_all_URLs(page: String): Set[String] =
|
|
|
658 |
http_pattern.findAllIn(page).map(unquote).toSet
|
|
|
659 |
|
|
|
660 |
// naive version of crawl - searches until a given depth,
|
|
|
661 |
// visits pages potentially more than once
|
|
318
|
662 |
def crawl(url: String, n: Int) : Unit = {
|
|
|
663 |
if (n == 0) ()
|
|
204
|
664 |
else {
|
|
|
665 |
println(s" Visiting: $n $url")
|
|
318
|
666 |
for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1)
|
|
204
|
667 |
}
|
|
147
|
668 |
}
|
|
|
669 |
|
|
204
|
670 |
// some starting URLs for the crawler
|
|
504
|
671 |
//val startURL = """https://nms.kcl.ac.uk/christian.urban/"""
|
|
|
672 |
val startURL = """https://urbanchr.github.io/"""
|
|
|
673 |
|
|
147
|
674 |
|
|
204
|
675 |
crawl(startURL, 2)
|
|
|
676 |
|
|
|
677 |
|
|
318
|
678 |
// a primitive email harvester
|
|
|
679 |
def emails(url: String, n: Int) : Set[String] = {
|
|
|
680 |
if (n == 0) Set()
|
|
|
681 |
else {
|
|
|
682 |
println(s" Visiting: $n $url")
|
|
|
683 |
val page = get_page(url)
|
|
|
684 |
val new_emails = email_pattern.findAllIn(page).toSet
|
|
|
685 |
new_emails ++ (for (u <- get_all_URLs(page)) yield emails(u, n - 1)).flatten
|
|
|
686 |
}
|
|
|
687 |
}
|
|
55
|
688 |
|
|
318
|
689 |
emails(startURL, 3)
|
|
55
|
690 |
|
|
|
691 |
|
|
318
|
692 |
// if we want to explore the internet "deeper", then we
|
|
|
693 |
// first have to parallelise the request of webpages:
|
|
|
694 |
//
|
|
|
695 |
// scala -cp scala-parallel-collections_2.13-0.2.0.jar
|
|
|
696 |
// import scala.collection.parallel.CollectionConverters._
|
|
55
|
697 |
|
|
53
|
698 |
|
|
|
699 |
|
|
504
|
700 |
def powerset(xs: Set[Int]) : Set[Set[Int]] = {
|
|
|
701 |
if (xs == Set()) Set(Set())
|
|
|
702 |
else {
|
|
|
703 |
val ps = powerset(xs.tail)
|
|
|
704 |
ps ++ ps.map(_ + xs.head)
|
|
|
705 |
}
|
|
|
706 |
}
|
|
53
|
707 |
|
|
504
|
708 |
def psubsets(xs: Set[Int]) =
|
|
|
709 |
powerset(xs) -- Set(Set(), xs)
|
|
|
710 |
|
|
|
711 |
//def psubsets(xs: Set[Int]) =
|
|
|
712 |
// xs.subsets.toList -- Set(Set(), xs)
|
|
|
713 |
|
|
|
714 |
def splits(xs: Set[Int]) : Set[(Set[Int], Set[Int])] =
|
|
|
715 |
psubsets(xs).map(s => (s, xs -- s))
|
|
|
716 |
|
|
|
717 |
|
|
|
718 |
|
|
|
719 |
enum Tree {
|
|
|
720 |
case Num(i: Int)
|
|
|
721 |
case Add(l: Tree, r: Tree)
|
|
|
722 |
case Sub(l: Tree, r: Tree)
|
|
|
723 |
case Mul(l: Tree, r: Tree)
|
|
|
724 |
case Div(l: Tree, r: Tree)
|
|
|
725 |
}
|
|
|
726 |
import Tree._
|
|
|
727 |
|
|
|
728 |
def pp(tr: Tree) : String = tr match {
|
|
|
729 |
case Num(n) => s"$n"
|
|
|
730 |
case Add(l, r) => s"(${pp(l)} + ${pp(r)})"
|
|
|
731 |
case Sub(l, r) => s"(${pp(l)} - ${pp(r)})"
|
|
|
732 |
case Mul(l, r) => s"(${pp(l)} * ${pp(r)})"
|
|
|
733 |
case Div(l, r) => s"(${pp(l)} / ${pp(r)})"
|
|
|
734 |
}
|
|
|
735 |
|
|
|
736 |
def search(nums: Set[Int]) : Set[Tree] = nums.size match {
|
|
|
737 |
case 0 => Set()
|
|
|
738 |
case 1 => Set(Num(nums.head))
|
|
|
739 |
case 2 => {
|
|
|
740 |
val l = nums.head
|
|
|
741 |
val r = nums.tail.head
|
|
|
742 |
Set(Add(Num(l), Num(r)),
|
|
|
743 |
Mul(Num(l), Num(r)))
|
|
|
744 |
++ Option.when(l <= r)(Sub(Num(r), Num(l)))
|
|
|
745 |
++ Option.when(l > r)(Sub(Num(l), Num(r)))
|
|
|
746 |
++ Option.when(r > 0 && l % r == 0)(Div(Num(l), Num(r)))
|
|
|
747 |
++ Option.when(l > 0 && r % l == 0)(Div(Num(r), Num(l)))
|
|
|
748 |
}
|
|
|
749 |
case xs => {
|
|
|
750 |
val spls = splits(nums)
|
|
|
751 |
val subtrs =
|
|
|
752 |
for ((lspls, rspls) <- spls;
|
|
|
753 |
lt <- search(lspls);
|
|
|
754 |
rt <- search(rspls)) yield {
|
|
|
755 |
Set(Add(lt, rt), Sub(lt, rt),
|
|
|
756 |
Mul(lt, rt), Div(lt, rt))
|
|
|
757 |
}
|
|
|
758 |
subtrs.flatten
|
|
|
759 |
}
|
|
|
760 |
}
|
|
|
761 |
|
|
|
762 |
println(search(Set(1,2,3,4)).mkString("\n"))
|
|
|
763 |
|
|
|
764 |
def eval(tr: Tree) : Option[Int] = tr match {
|
|
|
765 |
case Num(n) => Some(n)
|
|
|
766 |
case Add(l, r) =>
|
|
|
767 |
for (rl <- eval(l); rr <- eval(r)) yield rl + rr
|
|
|
768 |
case Mul(l, r) =>
|
|
|
769 |
for (rl <- eval(l); rr <- eval(r)) yield rl * rr
|
|
|
770 |
case Sub(l, r) =>
|
|
|
771 |
for (rl <- eval(l); rr <- eval(r);
|
|
|
772 |
if 0 <= rl - rr) yield rl - rr
|
|
|
773 |
case Div(l, r) =>
|
|
|
774 |
for (rl <- eval(l); rr <- eval(r);
|
|
|
775 |
if rr > 0 && rl % rr == 0) yield rl / rr
|
|
|
776 |
}
|
|
|
777 |
|
|
|
778 |
eval(Add(Num(1), Num(2)))
|
|
|
779 |
eval(Mul(Add(Num(1), Num(2)), Num(4)))
|
|
|
780 |
eval(Sub(Num(3), Num(2)))
|
|
|
781 |
eval(Sub(Num(3), Num(6)))
|
|
|
782 |
eval(Div(Num(6), Num(2)))
|
|
|
783 |
eval(Div(Num(6), Num(4)))
|
|
|
784 |
|
|
|
785 |
def time_needed[T](n: Int, code: => T) = {
|
|
|
786 |
val start = System.nanoTime()
|
|
|
787 |
for (i <- (0 to n)) code
|
|
|
788 |
val end = System.nanoTime()
|
|
|
789 |
(end - start) / 1.0e9
|
|
|
790 |
}
|
|
|
791 |
|
|
|
792 |
|
|
|
793 |
import scala.collection.parallel.CollectionConverters._
|
|
|
794 |
|
|
|
795 |
def check(xs: Set[Int], target: Int) =
|
|
|
796 |
search(xs).find(eval(_) == Some(target))
|
|
|
797 |
|
|
|
798 |
for (sol <- check(Set(50, 5, 4, 9, 10, 8), 560)) {
|
|
|
799 |
println(s"${pp(sol)} => ${eval(sol)}")
|
|
|
800 |
}
|
|
|
801 |
|
|
|
802 |
|
|
|
803 |
|
|
|
804 |
time_needed(1, check(Set(50, 5, 4, 9, 10, 8), 560))
|
|
|
805 |
|
|
|
806 |
|
|
|
807 |
println(check(Set(25, 5, 2, 10, 7, 1), 986).mkString("\n"))
|
|
|
808 |
|
|
|
809 |
for (sol <- check(Set(25, 5, 2, 10, 7, 1), 986)) {
|
|
|
810 |
println(s"${pp(sol)} => ${eval(sol)}")
|
|
|
811 |
}
|
|
|
812 |
|
|
|
813 |
for (sol <- check(Set(25, 5, 2, 10, 7, 1), -1)) {
|
|
|
814 |
println(s"${pp(sol)} => ${eval(sol)}")
|
|
|
815 |
}
|
|
|
816 |
|
|
|
817 |
for (sol <- check(Set(100, 25, 75, 50, 7, 10), 360)) {
|
|
|
818 |
println(s"${pp(sol)} => ${eval(sol)}")
|
|
|
819 |
}
|
|
|
820 |
time_needed(1, check(Set(100, 25, 75, 50, 7, 10), 360))
|
|
|
821 |
|
|
|
822 |
|
|
|
823 |
|
|
|
824 |
time_needed(1, check(Set(25, 5, 2, 10, 7, 1), 986))
|
|
|
825 |
time_needed(1, check(Set(25, 5, 2, 10, 7, 1), -1))
|
|
|
826 |
|
|
|
827 |
|
|
|
828 |
def generate(nums: Set[Int]) : Set[(Tree, Int)] = nums.size match {
|
|
|
829 |
case 0 => Set()
|
|
|
830 |
case 1 => Set((Num(nums.head), nums.head))
|
|
|
831 |
case xs => {
|
|
|
832 |
val spls = splits(nums)
|
|
|
833 |
val subtrs =
|
|
|
834 |
for ((lspls, rspls) <- spls;
|
|
|
835 |
(lt, ln) <- generate(lspls);
|
|
|
836 |
(rt, rn) <- generate(rspls)) yield {
|
|
|
837 |
Set((Add(lt, rt), ln + rn),
|
|
|
838 |
(Mul(lt, rt), ln * rn))
|
|
|
839 |
++ Option.when(ln <= rn)((Sub(rt, lt), rn - ln))
|
|
|
840 |
++ Option.when(ln > rn)((Sub(lt, rt), ln - rn))
|
|
|
841 |
++ Option.when(rn > 0 && ln % rn == 0)((Div(lt, rt), ln / rn))
|
|
|
842 |
++ Option.when(ln > 0 && rn % ln == 0)((Div(rt, lt), rn / ln))
|
|
|
843 |
}
|
|
|
844 |
subtrs.flatten
|
|
|
845 |
}
|
|
|
846 |
}
|
|
|
847 |
|
|
|
848 |
def check2(xs: Set[Int], target: Int) =
|
|
|
849 |
generate(xs).find(_._2 == target)
|
|
|
850 |
|
|
|
851 |
for ((sol, ev) <- check2(Set(50, 5, 4, 9, 10, 8), 560)) {
|
|
|
852 |
println(s"${pp(sol)} => ${eval(sol)} / $ev")
|
|
|
853 |
}
|
|
|
854 |
|
|
|
855 |
time_needed(1, check(Set(50, 5, 4, 9, 10, 8), 560))
|
|
|
856 |
time_needed(1, check2(Set(50, 5, 4, 9, 10, 8), 560))
|
|
|
857 |
|
|
|
858 |
time_needed(1, check(Set(50, 5, 4, 9, 10, 8), -1))
|
|
|
859 |
time_needed(1, check2(Set(50, 5, 4, 9, 10, 8), -1))
|
|
192
|
860 |
|
|
319
|
861 |
// Jumping Towers
|
|
|
862 |
//================
|
|
278
|
863 |
|
|
319
|
864 |
|
|
364
|
865 |
def moves(xs: List[Int], n: Int) : List[List[Int]] =
|
|
|
866 |
(xs, n) match {
|
|
|
867 |
case (Nil, _) => Nil
|
|
366
|
868 |
case (_, 0) => Nil
|
|
364
|
869 |
case (x::xs, n) => (x::xs) :: moves(xs, n - 1)
|
|
|
870 |
}
|
|
319
|
871 |
|
|
366
|
872 |
// List(5,5,1,0) -> moves(List(5,1,0), 5)
|
|
319
|
873 |
moves(List(5,1,0), 1)
|
|
|
874 |
moves(List(5,1,0), 2)
|
|
|
875 |
moves(List(5,1,0), 5)
|
|
|
876 |
|
|
|
877 |
// checks whether a jump tour exists at all
|
|
|
878 |
|
|
|
879 |
def search(xs: List[Int]) : Boolean = xs match {
|
|
|
880 |
case Nil => true
|
|
366
|
881 |
case x::xs =>
|
|
|
882 |
if (xs.length < x) true
|
|
|
883 |
else moves(xs, x).exists(search(_))
|
|
319
|
884 |
}
|
|
|
885 |
|
|
|
886 |
|
|
|
887 |
search(List(5,3,2,5,1,1))
|
|
|
888 |
search(List(3,5,1,0,0,0,1))
|
|
|
889 |
search(List(3,5,1,0,0,0,0,1))
|
|
|
890 |
search(List(3,5,1,0,0,0,1,1))
|
|
|
891 |
search(List(3,5,1))
|
|
|
892 |
search(List(5,1,1))
|
|
|
893 |
search(Nil)
|
|
|
894 |
search(List(1))
|
|
|
895 |
search(List(5,1,1))
|
|
|
896 |
search(List(3,5,1,0,0,0,0,0,0,0,0,1))
|
|
|
897 |
|
|
366
|
898 |
|
|
|
899 |
import scala.util._
|
|
|
900 |
List.fill(100)(Random.nextInt(2))
|
|
|
901 |
search(List.fill(100)(Random.nextInt(10)))
|
|
|
902 |
|
|
319
|
903 |
// generate *all* jump tours
|
|
|
904 |
// if we are only interested in the shortes one, we could
|
|
|
905 |
// shortcircut the calculation and only return List(x) in
|
|
|
906 |
// case where xs.length < x, because no tour can be shorter
|
|
|
907 |
// than 1
|
|
|
908 |
//
|
|
|
909 |
|
|
|
910 |
def jumps(xs: List[Int]) : List[List[Int]] = xs match {
|
|
|
911 |
case Nil => Nil
|
|
366
|
912 |
case x::xs => {
|
|
319
|
913 |
val children = moves(xs, x)
|
|
366
|
914 |
val results =
|
|
|
915 |
children.map(cs => jumps(cs).map(x :: _)).flatten
|
|
319
|
916 |
if (xs.length < x) List(x) :: results else results
|
|
|
917 |
}
|
|
|
918 |
}
|
|
|
919 |
|
|
|
920 |
jumps(List(3,5,1,2,1,2,1))
|
|
|
921 |
jumps(List(3,5,1,2,3,4,1))
|
|
|
922 |
jumps(List(3,5,1,0,0,0,1))
|
|
|
923 |
jumps(List(3,5,1))
|
|
|
924 |
jumps(List(5,1,1))
|
|
|
925 |
jumps(Nil)
|
|
|
926 |
jumps(List(1))
|
|
|
927 |
jumps(List(5,1,2))
|
|
|
928 |
moves(List(1,2), 5)
|
|
|
929 |
jumps(List(1,5,1,2))
|
|
|
930 |
jumps(List(3,5,1,0,0,0,0,0,0,0,0,1))
|
|
|
931 |
|
|
|
932 |
jumps(List(5,3,2,5,1,1)).minBy(_.length)
|
|
|
933 |
jumps(List(1,3,5,8,9,2,6,7,6,8,9)).minBy(_.length)
|
|
|
934 |
jumps(List(1,3,6,1,0,9)).minBy(_.length)
|
|
|
935 |
jumps(List(2,3,1,1,2,4,2,0,1,1)).minBy(_.length)
|
|
|
936 |
|
|
|
937 |
|