51
|
1 |
// Scala Lecture 1
|
|
2 |
//=================
|
14
|
3 |
|
26
|
4 |
// Value assignments
|
123
|
5 |
// (their names should be lower case)
|
|
6 |
//===================================
|
21
|
7 |
|
14
|
8 |
val x = 42
|
|
9 |
val y = 3 + 4
|
123
|
10 |
val z = x / y
|
|
11 |
|
|
12 |
|
|
13 |
// (you cannot reassign values: z = 9 will give an error)
|
14
|
14 |
|
|
15 |
|
125
|
16 |
// Hello World
|
|
17 |
//=============
|
|
18 |
|
|
19 |
// an example of a stand-alone scala file;
|
|
20 |
// in the coursework students must submit
|
|
21 |
// plain scala "work-sheets"
|
|
22 |
|
|
23 |
object Hello extends App {
|
|
24 |
println("hello world")
|
|
25 |
}
|
|
26 |
|
|
27 |
// can be called with
|
|
28 |
//
|
|
29 |
// $> scalac hello-world.scala
|
|
30 |
// $> scala Hello
|
|
31 |
//
|
|
32 |
// $> java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello
|
|
33 |
|
|
34 |
|
|
35 |
|
|
36 |
|
25
|
37 |
// Collections
|
|
38 |
//=============
|
14
|
39 |
List(1,2,3,1)
|
|
40 |
Set(1,2,3,1)
|
|
41 |
|
|
42 |
1 to 10
|
|
43 |
(1 to 10).toList
|
|
44 |
|
|
45 |
(1 until 10).toList
|
|
46 |
|
18
|
47 |
// an element in a list
|
33
|
48 |
val lst = List(1, 2, 3, 1)
|
|
49 |
lst(0)
|
|
50 |
lst(2)
|
18
|
51 |
|
34
|
52 |
// some alterative syntax for lists
|
|
53 |
|
189
|
54 |
1 :: 2 :: 3 :: Nil
|
23
|
55 |
List(1, 2, 3) ::: List(4, 5, 6)
|
14
|
56 |
|
25
|
57 |
// Printing/Strings
|
|
58 |
//==================
|
14
|
59 |
|
|
60 |
println("test")
|
15
|
61 |
|
33
|
62 |
val tst = "This is a " + "test\n"
|
14
|
63 |
println(tst)
|
|
64 |
|
|
65 |
val lst = List(1,2,3,1)
|
|
66 |
|
|
67 |
println(lst.toString)
|
|
68 |
println(lst.mkString("\n"))
|
|
69 |
|
33
|
70 |
println(lst.mkString(", "))
|
|
71 |
|
14
|
72 |
// some methods take more than one argument
|
21
|
73 |
println(lst.mkString("[", ",", "]"))
|
14
|
74 |
|
32
|
75 |
|
25
|
76 |
// Conversion methods
|
|
77 |
//====================
|
14
|
78 |
|
|
79 |
List(1,2,3,1).toString
|
|
80 |
List(1,2,3,1).toSet
|
|
81 |
"hello".toList
|
|
82 |
1.toDouble
|
|
83 |
|
25
|
84 |
|
32
|
85 |
// useful list methods
|
|
86 |
|
|
87 |
List(1,2,3,4).length
|
25
|
88 |
List(1,2,3,4).reverse
|
32
|
89 |
List(1,2,3,4).max
|
|
90 |
List(1,2,3,4).min
|
|
91 |
List(1,2,3,4).sum
|
|
92 |
List(1,2,3,4).take(2).sum
|
|
93 |
List(1,2,3,4).drop(2).sum
|
123
|
94 |
List(1,2,3,4,3)indexOf(3)
|
32
|
95 |
|
36
|
96 |
"1,2,3,4,5".split(",").mkString("\n")
|
|
97 |
"1,2,3,4,5".split(",3,").mkString("\n")
|
25
|
98 |
|
140
|
99 |
// Types (slide)
|
25
|
100 |
//=======
|
|
101 |
|
|
102 |
/* Scala is a strongly typed language
|
|
103 |
|
34
|
104 |
* some base types
|
14
|
105 |
|
25
|
106 |
Int, Long, BigInt, Float, Double
|
|
107 |
String, Char
|
|
108 |
Boolean
|
|
109 |
|
34
|
110 |
* some compound types
|
12
|
111 |
|
25
|
112 |
List[Int],
|
|
113 |
Set[Double]
|
|
114 |
Pairs: (Int, String)
|
|
115 |
List[(BigInt, String)]
|
|
116 |
*/
|
12
|
117 |
|
25
|
118 |
// Smart Strings
|
|
119 |
//===============
|
|
120 |
|
36
|
121 |
println(">\n\n<")
|
23
|
122 |
println(""">\n<""")
|
36
|
123 |
println("""">\n<"""")
|
23
|
124 |
|
|
125 |
/* in Java
|
143
|
126 |
val lyrics = "Sun dips down, the day has gone. \n" +
|
|
127 |
"Witches, wolves and giants yawn. \n" +
|
|
128 |
"Queen and dragon, troll and gnome: \n" +
|
189
|
129 |
"tired buddies head for home."
|
23
|
130 |
*/
|
|
131 |
|
143
|
132 |
val lyrics = """Sun dips down, the day has gone.
|
|
133 |
|Witches, wolves and giants yawn.
|
|
134 |
|Queen and dragon, troll and gnome:
|
189
|
135 |
|tired buddies head for home.""".stripMargin
|
23
|
136 |
|
|
137 |
println(lyrics)
|
|
138 |
|
14
|
139 |
|
25
|
140 |
// Pairs/Tuples
|
|
141 |
//==============
|
14
|
142 |
|
|
143 |
val p = (1, "one")
|
|
144 |
p._1
|
|
145 |
p._2
|
|
146 |
|
|
147 |
val t = (4,1,2,3)
|
|
148 |
t._4
|
|
149 |
|
25
|
150 |
|
|
151 |
// Function Definitions
|
|
152 |
//======================
|
14
|
153 |
|
123
|
154 |
def incr(x: Int) : Int = x + 1
|
|
155 |
def double(x: Int) : Int = x + x
|
|
156 |
def square(x: Int) : Int = x * x
|
14
|
157 |
|
25
|
158 |
square(6)
|
21
|
159 |
|
|
160 |
|
36
|
161 |
|
|
162 |
// The general scheme for a function: you have to give a type
|
|
163 |
// to each argument and a return type of the function
|
|
164 |
//
|
|
165 |
// def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
|
|
166 |
// body
|
|
167 |
// }
|
|
168 |
|
|
169 |
|
|
170 |
|
123
|
171 |
// If-Conditionals
|
|
172 |
//=================
|
14
|
173 |
|
189
|
174 |
// Scala does not have a then-keyword
|
|
175 |
// both if-else branches need to be presents
|
|
176 |
|
143
|
177 |
def fact(n: Int) : Int =
|
14
|
178 |
if (n == 0) 1 else n * fact(n - 1)
|
|
179 |
|
36
|
180 |
|
|
181 |
fact(5)
|
|
182 |
fact(150)
|
|
183 |
|
25
|
184 |
/* boolean operators
|
|
185 |
|
|
186 |
== equals
|
|
187 |
! not
|
|
188 |
&& || and, or
|
|
189 |
*/
|
15
|
190 |
|
|
191 |
|
189
|
192 |
def fact2(n: BigInt) : BigInt =
|
14
|
193 |
if (n == 0) 1 else n * fact2(n - 1)
|
|
194 |
|
25
|
195 |
fact2(150)
|
|
196 |
|
26
|
197 |
|
189
|
198 |
def fib(n: Int) : Int =
|
14
|
199 |
if (n == 0) 1 else
|
26
|
200 |
if (n == 1) 1 else fib(n - 1) + fib(n - 2)
|
14
|
201 |
|
|
202 |
|
26
|
203 |
//gcd - Euclid's algorithm
|
|
204 |
|
123
|
205 |
def gcd(a: Int, b: Int) : Int =
|
26
|
206 |
if (b == 0) a else gcd(b, a % b)
|
|
207 |
|
|
208 |
gcd(48, 18)
|
|
209 |
|
14
|
210 |
|
123
|
211 |
def power(x: Int, n: Int) : Int =
|
|
212 |
if (n == 0) 1 else x * power(x, n - 1)
|
|
213 |
|
|
214 |
power(5, 5)
|
|
215 |
|
|
216 |
|
25
|
217 |
// String Interpolations
|
|
218 |
//=======================
|
14
|
219 |
|
26
|
220 |
val n = 3
|
|
221 |
println("The square of " + n + " is " + square(n) + ".")
|
|
222 |
|
|
223 |
println(s"The square of ${n} is ${square(n)}.")
|
|
224 |
|
|
225 |
|
|
226 |
|
123
|
227 |
def gcd_db(a: Int, b: Int) : Int = {
|
26
|
228 |
println(s"Function called with ${a} and ${b}.")
|
|
229 |
if (b == 0) a else gcd_db(b, a % b)
|
|
230 |
}
|
|
231 |
|
|
232 |
gcd_db(48, 18)
|
|
233 |
|
14
|
234 |
|
124
|
235 |
// Asserts/Testing
|
25
|
236 |
//================
|
14
|
237 |
|
32
|
238 |
assert(gcd(48, 18) == 6)
|
|
239 |
|
|
240 |
assert(gcd(48, 18) == 5, "The gcd test failed")
|
|
241 |
|
|
242 |
|
26
|
243 |
// For-Comprehensions (not For-Loops)
|
|
244 |
//====================================
|
14
|
245 |
|
|
246 |
for (n <- (1 to 10).toList) yield square(n)
|
|
247 |
|
25
|
248 |
for (n <- (1 to 10).toList;
|
|
249 |
m <- (1 to 10).toList) yield m * n
|
21
|
250 |
|
|
251 |
|
26
|
252 |
val mult_table =
|
|
253 |
for (n <- (1 to 10).toList;
|
|
254 |
m <- (1 to 10).toList) yield m * n
|
|
255 |
|
|
256 |
mult_table.sliding(10,10).mkString("\n")
|
|
257 |
|
189
|
258 |
// the list can also be constructed in any other way
|
|
259 |
for (n <- List(10,12,4,5,7,8,10)) yield n * n
|
|
260 |
|
25
|
261 |
|
32
|
262 |
// with if-predicates
|
|
263 |
|
|
264 |
for (n <- (1 to 3).toList;
|
|
265 |
m <- (1 to 3).toList;
|
|
266 |
if (n + m) % 2 == 0) yield (n, m)
|
|
267 |
|
148
|
268 |
for (n <- (1 to 3).toList;
|
|
269 |
m <- (1 to 3).toList;
|
|
270 |
if ((n + m) % 2 == 0)) yield (n, m)
|
32
|
271 |
|
26
|
272 |
// with patterns
|
|
273 |
|
|
274 |
for ((m, n) <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield m + n
|
|
275 |
|
|
276 |
for (p <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield p._1 + p._2
|
|
277 |
|
25
|
278 |
|
189
|
279 |
// general pattern
|
|
280 |
|
|
281 |
for (x <- ...) yield {
|
|
282 |
// potentially complicated
|
|
283 |
// calculation of a result
|
|
284 |
}
|
|
285 |
|
|
286 |
|
25
|
287 |
|
36
|
288 |
// with only a side-effect (no list is produced),
|
32
|
289 |
// has no "yield"
|
|
290 |
|
|
291 |
for (n <- (1 to 10)) println(n)
|
|
292 |
|
|
293 |
|
140
|
294 |
|
|
295 |
// concurrency (ONLY WORKS IN SCALA 2.11.8, not in SCALA 2.12)
|
|
296 |
// (would need to have this wrapped into a function, or
|
|
297 |
// REPL called with scala -Yrepl-class-based)
|
32
|
298 |
for (n <- (1 to 10)) println(n)
|
|
299 |
for (n <- (1 to 10).par) println(n)
|
|
300 |
|
|
301 |
|
36
|
302 |
// for measuring time
|
140
|
303 |
def time_needed[T](n: Int, code: => T) = {
|
32
|
304 |
val start = System.nanoTime()
|
140
|
305 |
for (i <- (0 to n)) code
|
32
|
306 |
val end = System.nanoTime()
|
140
|
307 |
(end - start) / 1.0e9
|
32
|
308 |
}
|
|
309 |
|
140
|
310 |
|
32
|
311 |
val list = (1 to 1000000).toList
|
|
312 |
time_needed(10, for (n <- list) yield n + 42)
|
|
313 |
time_needed(10, for (n <- list.par) yield n + 42)
|
|
314 |
|
|
315 |
|
170
|
316 |
// mutable vs immutable factorial
|
189
|
317 |
def fact_mu(n: Long) : Long = {
|
170
|
318 |
var result : Long = 1
|
|
319 |
var i = 1
|
|
320 |
while (i <= n) {
|
|
321 |
result = result * i
|
|
322 |
i = i + 1
|
|
323 |
}
|
|
324 |
result
|
|
325 |
}
|
140
|
326 |
|
170
|
327 |
def fact_im(num: Long): Long = {
|
|
328 |
if (num == 1) num else
|
|
329 |
num * fact_im(num - 1)
|
|
330 |
}
|
140
|
331 |
|
170
|
332 |
def test() = {
|
|
333 |
for (i <- (0 to 10).par) yield {
|
|
334 |
val l1 = for (n <- (List.fill(100000)(20 to 21)).flatten.par) yield fact_mu(n)
|
|
335 |
val l2 = for (n <- (List.fill(100000)(20 to 21)).flatten.par) yield fact_im(n)
|
|
336 |
l1.sum - l2.sum
|
|
337 |
}
|
|
338 |
}
|
|
339 |
|
189
|
340 |
(for (i <- (1 to 10)) yield test().sum).sum
|
|
341 |
|
140
|
342 |
|
25
|
343 |
// Webpages
|
|
344 |
//==========
|
32
|
345 |
|
|
346 |
import io.Source
|
|
347 |
|
36
|
348 |
// obtaining a webpage
|
123
|
349 |
val url = """https://nms.kcl.ac.uk/christian.urban/"""
|
32
|
350 |
Source.fromURL(url)("ISO-8859-1").mkString
|
|
351 |
|
|
352 |
|
140
|
353 |
// another example
|
|
354 |
//val url = """http://api.postcodes.io/postcodes/CR84LQ"""
|
|
355 |
|
|
356 |
|
137
|
357 |
// a function for looking up constituency data
|
|
358 |
def consty_lookup(pcode: String) : String = {
|
|
359 |
val url = "http://api.postcodes.io/postcodes/" + pcode
|
|
360 |
Source.fromURL(url).mkString.split(",")(16)
|
32
|
361 |
}
|
|
362 |
|
137
|
363 |
consty_lookup("CR84LQ")
|
|
364 |
consty_lookup("WC2B4BG")
|
32
|
365 |
|
|
366 |
|
137
|
367 |
val places =
|
|
368 |
List("CR84LQ", "WC2B4BG", "KY169QT", "CB11LY", "CB39AX")
|
32
|
369 |
|
137
|
370 |
for (s <- places) println(consty_lookup(s))
|
|
371 |
|
|
372 |
|
32
|
373 |
|
|
374 |
|
123
|
375 |
// A Web Crawler
|
32
|
376 |
//===============
|
36
|
377 |
//
|
123
|
378 |
// the idea is to look for dead links using the
|
|
379 |
// regular expression "https?://[^"]*"
|
32
|
380 |
|
|
381 |
import io.Source
|
|
382 |
import scala.util._
|
|
383 |
|
|
384 |
// gets the first 10K of a web-page
|
|
385 |
def get_page(url: String) : String = {
|
|
386 |
Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
|
|
387 |
getOrElse { println(s" Problem with: $url"); ""}
|
|
388 |
}
|
|
389 |
|
|
390 |
// regex for URLs
|
|
391 |
val http_pattern = """"https?://[^"]*"""".r
|
|
392 |
|
|
393 |
// drops the first and last character from a string
|
|
394 |
def unquote(s: String) = s.drop(1).dropRight(1)
|
|
395 |
|
|
396 |
def get_all_URLs(page: String): Set[String] =
|
|
397 |
http_pattern.findAllIn(page).map(unquote).toSet
|
|
398 |
|
|
399 |
// naive version of crawl - searches until a given depth,
|
|
400 |
// visits pages potentially more than once
|
140
|
401 |
def crawl(url: String, n: Int) : Unit = {
|
32
|
402 |
if (n == 0) ()
|
|
403 |
else {
|
|
404 |
println(s"Visiting: $n $url")
|
|
405 |
for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1)
|
|
406 |
}
|
|
407 |
}
|
|
408 |
|
|
409 |
// some starting URLs for the crawler
|
123
|
410 |
val startURL = """https://nms.kcl.ac.uk/christian.urban/"""
|
137
|
411 |
//val startURL = """https://nms.kcl.ac.uk/luc.moreau/index.html"""
|
32
|
412 |
|
|
413 |
crawl(startURL, 2)
|
|
414 |
|
|
415 |
|
|
416 |
|
|
417 |
// Further Information
|
|
418 |
//=====================
|
|
419 |
|
123
|
420 |
// The Scala home page and general information is at
|
32
|
421 |
//
|
|
422 |
// http://www.scala-lang.org
|
123
|
423 |
// http://docs.scala-lang.org
|
|
424 |
//
|
|
425 |
//
|
|
426 |
// It should be fairly easy to install the Scala binary and
|
|
427 |
// run Scala on the commandline. There are also at least
|
|
428 |
// four IDEs you can use with Scala:
|
|
429 |
//
|
124
|
430 |
// (0) Some general information about setting up IDEs
|
123
|
431 |
// with Scala support can be found at
|
|
432 |
//
|
|
433 |
// http://docs.scala-lang.org/getting-started.html
|
|
434 |
//
|
124
|
435 |
//
|
123
|
436 |
// (1) Eclipse for Scala (one big bundle)
|
|
437 |
//
|
|
438 |
// http://scala-ide.org/download/sdk.html
|
|
439 |
//
|
|
440 |
// (2) IntelliJ (needs additional Plugins)
|
|
441 |
//
|
|
442 |
// https://www.jetbrains.com/idea/
|
|
443 |
// http://docs.scala-lang.org/getting-started-intellij-track/getting-started-with-scala-in-intellij.html
|
|
444 |
//
|
|
445 |
// (3) Sublime (not free, but unlimited trial period;
|
124
|
446 |
// needs Scala and SublimeREPL plugin)
|
123
|
447 |
//
|
|
448 |
// https://www.sublimetext.com
|
|
449 |
//
|
|
450 |
// (4) Emacs (old-fashioned, but reliable)
|
|
451 |
//
|
|
452 |
// https://www.gnu.org/software/emacs/
|
32
|
453 |
//
|
123
|
454 |
// I use the old scala-tool support for Emacs distributed at
|
|
455 |
//
|
|
456 |
// https://github.com/scala/scala-tool-support/tree/master/tool-support/emacs
|
|
457 |
//
|
|
458 |
// but there is also support for the newer Ensime Scala Mode
|
|
459 |
//
|
|
460 |
// http://ensime.org/editors/emacs/scala-mode/
|
|
461 |
//
|
|
462 |
// There is also Scala support in the Atom editor, but my
|
|
463 |
// experience is mixed. People also use Scala with Vim and Jedit.
|
124
|
464 |
// Finally there is an online editor specifically designed for
|
|
465 |
// running Scala applications (but do not blame mne if you lose all
|
|
466 |
// what you typed in):
|
|
467 |
//
|
|
468 |
// https://scalafiddle.io
|
|
469 |
//
|
|
470 |
//
|
123
|
471 |
//
|
|
472 |
// All of the IDEs above support a REPL for Scala. Some of them have
|
|
473 |
// the very nifty feature of a Scala Worksheet -- you just save your
|
|
474 |
// file and it will be automatically evaluated and the result pasted
|
|
475 |
// into your file. However, this way of writing Scala code never worked
|
|
476 |
// for me. I just use the REPL.
|
|
477 |
//
|
|
478 |
//
|
|
479 |
// Scala Library Docs
|
124
|
480 |
//====================
|
123
|
481 |
//
|
|
482 |
// http://www.scala-lang.org/api/current/
|
|
483 |
//
|
|
484 |
// Scala Tutorials
|
|
485 |
//
|
|
486 |
// http://docs.scala-lang.org/tutorials/
|
|
487 |
//
|
|
488 |
// There are also a massive number of Scala tutorials on youtube
|
|
489 |
// and there are tons of books and free material.
|
|
490 |
//
|
32
|
491 |
|
|
492 |
|
170
|
493 |
|
|
494 |
|
|
495 |
|
|
496 |
|
|
497 |
|
|
498 |
|
|
499 |
|
|
500 |
// advantage of case classes
|
|
501 |
//
|
|
502 |
case class Participant(name: String, score: Int, active: Boolean)
|
|
503 |
|
|
504 |
val ps = Seq(Participant("Jack", 34, true),
|
|
505 |
Participant("Tom", 51, true),
|
|
506 |
Participant("Bob", 90, false))
|
|
507 |
|
|
508 |
ps.filter(_.score < 50).
|
|
509 |
filter(_.active).
|
|
510 |
map(_.copy(active = false))
|
|
511 |
|
|
512 |
|
|
513 |
|
|
514 |
// another example why state is bad...does not work yet
|
|
515 |
|
|
516 |
// for measuring time
|
|
517 |
def time_needed[T](n: Int, code: => T) = {
|
|
518 |
val start = System.nanoTime()
|
|
519 |
for (i <- (0 to n)) code
|
|
520 |
val end = System.nanoTime()
|
|
521 |
(end - start) / 1.0e9
|
|
522 |
}
|
|
523 |
|
|
524 |
def santa_state(plan: List[Char]) : Int = {
|
|
525 |
|
|
526 |
var floor = 0
|
|
527 |
|
|
528 |
for (i <- plan.par) {
|
|
529 |
if (i == '(') {
|
|
530 |
floor += 1
|
|
531 |
} else {
|
|
532 |
floor -= 1
|
|
533 |
}
|
|
534 |
}
|
|
535 |
|
|
536 |
floor
|
|
537 |
}
|
|
538 |
|
|
539 |
def i(c: Char) = if (c == '(') 1 else -1
|
|
540 |
|
|
541 |
def santa_imutable(plan: List[Char]) : Int =
|
|
542 |
plan.par.map(i(_)).reduce(_ + _)
|
|
543 |
|
|
544 |
santa_state("(((((()))))".toList)
|
|
545 |
santa_imutable("(((((()))))".toList)
|
|
546 |
|
189
|
547 |
def randomString(length: Int) : String =
|
170
|
548 |
List.fill(length)((40 + scala.util.Random.nextInt(2)).toChar)
|
|
549 |
|
|
550 |
|
|
551 |
santa_state(randomString(100))
|
|
552 |
|
|
553 |
val large_string = randomString(3000000)
|
|
554 |
|
|
555 |
time_needed(10, santa_state(large_string))
|
|
556 |
time_needed(10, santa_imutable(large_string))
|