51
|
1 |
// Scala Lecture 1
|
|
2 |
//=================
|
14
|
3 |
|
26
|
4 |
// Value assignments
|
123
|
5 |
// (their names should be lower case)
|
199
|
6 |
//====================================
|
21
|
7 |
|
202
|
8 |
|
14
|
9 |
val x = 42
|
|
10 |
val y = 3 + 4
|
123
|
11 |
val z = x / y
|
|
12 |
|
|
13 |
// (you cannot reassign values: z = 9 will give an error)
|
14
|
14 |
|
|
15 |
|
125
|
16 |
// Hello World
|
|
17 |
//=============
|
|
18 |
|
199
|
19 |
// an example of a stand-alone Scala file
|
|
20 |
// (in the assignments you must submit a plain Scala script)
|
125
|
21 |
|
|
22 |
object Hello extends App {
|
|
23 |
println("hello world")
|
|
24 |
}
|
|
25 |
|
199
|
26 |
// can then be called with
|
125
|
27 |
//
|
|
28 |
// $> scalac hello-world.scala
|
|
29 |
// $> scala Hello
|
|
30 |
//
|
|
31 |
// $> java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello
|
|
32 |
|
|
33 |
|
|
34 |
|
25
|
35 |
// Collections
|
|
36 |
//=============
|
14
|
37 |
List(1,2,3,1)
|
|
38 |
Set(1,2,3,1)
|
|
39 |
|
|
40 |
1 to 10
|
|
41 |
(1 to 10).toList
|
|
42 |
|
|
43 |
(1 until 10).toList
|
|
44 |
|
18
|
45 |
// an element in a list
|
33
|
46 |
val lst = List(1, 2, 3, 1)
|
|
47 |
lst(0)
|
|
48 |
lst(2)
|
18
|
49 |
|
34
|
50 |
// some alterative syntax for lists
|
|
51 |
|
189
|
52 |
1 :: 2 :: 3 :: Nil
|
23
|
53 |
List(1, 2, 3) ::: List(4, 5, 6)
|
14
|
54 |
|
199
|
55 |
// Equality is structural
|
|
56 |
//========================
|
|
57 |
val a = "Dave"
|
|
58 |
val b = "Dave"
|
|
59 |
|
202
|
60 |
if (a == b) println("Equal") else println("Unequal")
|
199
|
61 |
|
|
62 |
Set(1,2,3) == Set(3,1,2)
|
|
63 |
List(1,2,3) == List(3,1,2)
|
|
64 |
|
202
|
65 |
val n1 = 3 + 7
|
|
66 |
val n2 = 5 + 5
|
|
67 |
|
|
68 |
n1 == n2
|
199
|
69 |
|
200
|
70 |
// this applies to "concrete" values;
|
199
|
71 |
// you cannot compare functions
|
|
72 |
|
|
73 |
|
25
|
74 |
// Printing/Strings
|
|
75 |
//==================
|
14
|
76 |
|
|
77 |
println("test")
|
15
|
78 |
|
33
|
79 |
val tst = "This is a " + "test\n"
|
14
|
80 |
println(tst)
|
|
81 |
|
|
82 |
val lst = List(1,2,3,1)
|
|
83 |
|
202
|
84 |
|
14
|
85 |
println(lst.toString)
|
202
|
86 |
println(lst.mkString(","))
|
14
|
87 |
|
33
|
88 |
println(lst.mkString(", "))
|
|
89 |
|
14
|
90 |
// some methods take more than one argument
|
202
|
91 |
println(lst.mkString("{", ",", "}"))
|
14
|
92 |
|
32
|
93 |
|
200
|
94 |
|
25
|
95 |
// Conversion methods
|
|
96 |
//====================
|
14
|
97 |
|
|
98 |
List(1,2,3,1).toString
|
|
99 |
List(1,2,3,1).toSet
|
202
|
100 |
"hello".toList.tail
|
14
|
101 |
1.toDouble
|
|
102 |
|
25
|
103 |
|
32
|
104 |
// useful list methods
|
|
105 |
|
|
106 |
List(1,2,3,4).length
|
25
|
107 |
List(1,2,3,4).reverse
|
32
|
108 |
List(1,2,3,4).max
|
|
109 |
List(1,2,3,4).min
|
|
110 |
List(1,2,3,4).sum
|
|
111 |
List(1,2,3,4).take(2).sum
|
|
112 |
List(1,2,3,4).drop(2).sum
|
199
|
113 |
List(1,2,3,4,3).indexOf(3)
|
32
|
114 |
|
36
|
115 |
"1,2,3,4,5".split(",").mkString("\n")
|
202
|
116 |
"1,2,3,4,5".split(",").toList
|
36
|
117 |
"1,2,3,4,5".split(",3,").mkString("\n")
|
25
|
118 |
|
200
|
119 |
"abcdefg".startsWith("abc")
|
|
120 |
|
|
121 |
|
140
|
122 |
// Types (slide)
|
200
|
123 |
//===============
|
25
|
124 |
|
|
125 |
/* Scala is a strongly typed language
|
|
126 |
|
34
|
127 |
* some base types
|
14
|
128 |
|
25
|
129 |
Int, Long, BigInt, Float, Double
|
|
130 |
String, Char
|
|
131 |
Boolean
|
|
132 |
|
34
|
133 |
* some compound types
|
12
|
134 |
|
25
|
135 |
List[Int],
|
|
136 |
Set[Double]
|
|
137 |
Pairs: (Int, String)
|
|
138 |
List[(BigInt, String)]
|
200
|
139 |
Option[Int]
|
25
|
140 |
*/
|
12
|
141 |
|
23
|
142 |
|
14
|
143 |
|
25
|
144 |
// Pairs/Tuples
|
|
145 |
//==============
|
14
|
146 |
|
|
147 |
val p = (1, "one")
|
|
148 |
p._1
|
|
149 |
p._2
|
|
150 |
|
|
151 |
val t = (4,1,2,3)
|
|
152 |
t._4
|
|
153 |
|
25
|
154 |
|
200
|
155 |
List(("one", 1), ("two", 2), ("three", 3))
|
|
156 |
|
25
|
157 |
// Function Definitions
|
|
158 |
//======================
|
14
|
159 |
|
123
|
160 |
def incr(x: Int) : Int = x + 1
|
|
161 |
def double(x: Int) : Int = x + x
|
|
162 |
def square(x: Int) : Int = x * x
|
14
|
163 |
|
202
|
164 |
def str(x: Int) : String = x.toString
|
25
|
165 |
square(6)
|
21
|
166 |
|
|
167 |
|
36
|
168 |
// The general scheme for a function: you have to give a type
|
|
169 |
// to each argument and a return type of the function
|
|
170 |
//
|
|
171 |
// def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
|
|
172 |
// body
|
|
173 |
// }
|
|
174 |
|
|
175 |
|
200
|
176 |
//
|
|
177 |
// BTW: no returns!!
|
|
178 |
// "last" line (expression) in a function determines the result
|
|
179 |
//
|
|
180 |
|
|
181 |
def silly(n: Int) : Int = {
|
202
|
182 |
if (n < 10) n * n
|
|
183 |
else n + n
|
200
|
184 |
}
|
|
185 |
|
36
|
186 |
|
123
|
187 |
// If-Conditionals
|
|
188 |
//=================
|
14
|
189 |
|
200
|
190 |
// - Scala does not have a then-keyword
|
|
191 |
// - both if-else branches need to be present
|
189
|
192 |
|
143
|
193 |
def fact(n: Int) : Int =
|
14
|
194 |
if (n == 0) 1 else n * fact(n - 1)
|
|
195 |
|
36
|
196 |
|
|
197 |
fact(5)
|
|
198 |
fact(150)
|
|
199 |
|
25
|
200 |
/* boolean operators
|
|
201 |
|
|
202 |
== equals
|
|
203 |
! not
|
|
204 |
&& || and, or
|
|
205 |
*/
|
15
|
206 |
|
|
207 |
|
189
|
208 |
def fact2(n: BigInt) : BigInt =
|
14
|
209 |
if (n == 0) 1 else n * fact2(n - 1)
|
|
210 |
|
25
|
211 |
fact2(150)
|
|
212 |
|
26
|
213 |
|
189
|
214 |
def fib(n: Int) : Int =
|
14
|
215 |
if (n == 0) 1 else
|
26
|
216 |
if (n == 1) 1 else fib(n - 1) + fib(n - 2)
|
14
|
217 |
|
|
218 |
|
26
|
219 |
//gcd - Euclid's algorithm
|
|
220 |
|
202
|
221 |
def gcd(a: Int, b: Int) : Int = {
|
|
222 |
if (b == 0) a
|
|
223 |
else {
|
|
224 |
val foo = 42
|
|
225 |
gcd(b, a % b)
|
|
226 |
}
|
|
227 |
}
|
26
|
228 |
|
|
229 |
gcd(48, 18)
|
|
230 |
|
14
|
231 |
|
123
|
232 |
def power(x: Int, n: Int) : Int =
|
199
|
233 |
if (n == 0) 1 else x * power(x, n - 1)
|
123
|
234 |
|
|
235 |
power(5, 5)
|
|
236 |
|
|
237 |
|
199
|
238 |
// Option type
|
|
239 |
//=============
|
|
240 |
|
|
241 |
//in Java if something unusually happens, you return null
|
|
242 |
//
|
200
|
243 |
//in Scala you use Options instead
|
199
|
244 |
// - if the value is present, you use Some(value)
|
|
245 |
// - if no value is present, you use None
|
|
246 |
|
|
247 |
|
|
248 |
List(7,2,3,4,5,6).find(_ < 4)
|
|
249 |
List(5,6,7,8,9).find(_ < 4)
|
|
250 |
|
|
251 |
|
|
252 |
|
|
253 |
// error handling with Options (no exceptions)
|
|
254 |
//
|
|
255 |
// Try(something).getOrElse(what_to_do_in_case_of_an_exception)
|
|
256 |
//
|
|
257 |
import scala.util._
|
|
258 |
import io.Source
|
|
259 |
|
202
|
260 |
val my_url = "https://nms.imperial.ac.uk/christian.urban/"
|
199
|
261 |
|
|
262 |
Source.fromURL(my_url).mkString
|
|
263 |
|
|
264 |
Try(Source.fromURL(my_url).mkString).getOrElse("")
|
|
265 |
|
|
266 |
Try(Some(Source.fromURL(my_url).mkString)).getOrElse(None)
|
|
267 |
|
|
268 |
|
|
269 |
// the same for files
|
202
|
270 |
Try(Some(Source.fromFile("text.txt").mkString)).getOrElse(None)
|
199
|
271 |
|
200
|
272 |
// function reading something from files...
|
|
273 |
|
|
274 |
def get_contents(name: String) : List[String] =
|
|
275 |
Source.fromFile(name).getLines.toList
|
|
276 |
|
|
277 |
get_contents("test.txt")
|
|
278 |
|
|
279 |
// slightly better - return Nil
|
|
280 |
def get_contents(name: String) : List[String] =
|
202
|
281 |
Try(Source.fromFile(name).getLines.toList).getOrElse(List())
|
200
|
282 |
|
|
283 |
get_contents("text.txt")
|
|
284 |
|
|
285 |
// much better - you record in the type that things can go wrong
|
|
286 |
def get_contents(name: String) : Option[List[String]] =
|
|
287 |
Try(Some(Source.fromFile(name).getLines.toList)).getOrElse(None)
|
|
288 |
|
|
289 |
get_contents("text.txt")
|
|
290 |
|
|
291 |
|
199
|
292 |
|
25
|
293 |
// String Interpolations
|
|
294 |
//=======================
|
14
|
295 |
|
26
|
296 |
val n = 3
|
|
297 |
println("The square of " + n + " is " + square(n) + ".")
|
|
298 |
|
|
299 |
println(s"The square of ${n} is ${square(n)}.")
|
|
300 |
|
|
301 |
|
200
|
302 |
// helpful for debugging purposes
|
|
303 |
//
|
|
304 |
// "The most effective debugging tool is still careful thought,
|
|
305 |
// coupled with judiciously placed print statements."
|
|
306 |
// — Brian W. Kernighan, in Unix for Beginners (1979)
|
|
307 |
|
26
|
308 |
|
123
|
309 |
def gcd_db(a: Int, b: Int) : Int = {
|
26
|
310 |
println(s"Function called with ${a} and ${b}.")
|
|
311 |
if (b == 0) a else gcd_db(b, a % b)
|
|
312 |
}
|
|
313 |
|
|
314 |
gcd_db(48, 18)
|
|
315 |
|
14
|
316 |
|
124
|
317 |
// Asserts/Testing
|
200
|
318 |
//=================
|
14
|
319 |
|
32
|
320 |
assert(gcd(48, 18) == 6)
|
|
321 |
|
|
322 |
assert(gcd(48, 18) == 5, "The gcd test failed")
|
|
323 |
|
|
324 |
|
26
|
325 |
// For-Comprehensions (not For-Loops)
|
|
326 |
//====================================
|
14
|
327 |
|
202
|
328 |
|
|
329 |
for (n <- (1 to 10).toList) yield {
|
|
330 |
square(n) + 1
|
|
331 |
}
|
14
|
332 |
|
25
|
333 |
for (n <- (1 to 10).toList;
|
|
334 |
m <- (1 to 10).toList) yield m * n
|
21
|
335 |
|
|
336 |
|
26
|
337 |
val mult_table =
|
|
338 |
for (n <- (1 to 10).toList;
|
|
339 |
m <- (1 to 10).toList) yield m * n
|
|
340 |
|
202
|
341 |
println(mult_table.mkString)
|
26
|
342 |
mult_table.sliding(10,10).mkString("\n")
|
|
343 |
|
200
|
344 |
// the list/set/... can also be constructed in any
|
|
345 |
// other way
|
202
|
346 |
for (n <- Set(10,12,4,5,7,8,10)) yield n * n
|
189
|
347 |
|
25
|
348 |
|
200
|
349 |
// with if-predicates / filters
|
32
|
350 |
|
|
351 |
for (n <- (1 to 3).toList;
|
|
352 |
m <- (1 to 3).toList;
|
202
|
353 |
if (n + m) % 2 == 0;
|
|
354 |
if (n * m) < 2) yield (n, m)
|
32
|
355 |
|
148
|
356 |
for (n <- (1 to 3).toList;
|
|
357 |
m <- (1 to 3).toList;
|
202
|
358 |
if ((((n + m) % 2 == 0)))) yield (n, m)
|
32
|
359 |
|
26
|
360 |
// with patterns
|
|
361 |
|
199
|
362 |
val lst = List((1, 4), (2, 3), (3, 2), (4, 1))
|
26
|
363 |
|
199
|
364 |
for ((m, n) <- lst) yield m + n
|
|
365 |
|
|
366 |
for (p <- lst) yield p._1 + p._2
|
26
|
367 |
|
25
|
368 |
|
200
|
369 |
// general pattern of for-yield
|
189
|
370 |
|
200
|
371 |
for (p <- ...) yield {
|
189
|
372 |
// potentially complicated
|
|
373 |
// calculation of a result
|
|
374 |
}
|
|
375 |
|
200
|
376 |
// Functions producing multiple outputs
|
|
377 |
//======================================
|
189
|
378 |
|
200
|
379 |
def get_ascii(c: Char) : (Char, Int) = (c, c.toInt)
|
|
380 |
|
|
381 |
get_ascii('a')
|
|
382 |
|
|
383 |
|
|
384 |
// .maxBy, sortBy with pairs
|
|
385 |
def get_length(s: String) : (String, Int) = (s, s.length)
|
|
386 |
|
|
387 |
val lst = List("zero", "one", "two", "three", "four", "ten")
|
|
388 |
val strs = for (s <- lst) yield get_length(s)
|
|
389 |
|
|
390 |
strs.sortBy(_._2)
|
|
391 |
strs.sortBy(_._1)
|
|
392 |
|
|
393 |
strs.maxBy(_._2)
|
|
394 |
strs.maxBy(_._1)
|
|
395 |
|
|
396 |
|
|
397 |
// For without yield
|
|
398 |
//===================
|
25
|
399 |
|
36
|
400 |
// with only a side-effect (no list is produced),
|
32
|
401 |
// has no "yield"
|
|
402 |
|
|
403 |
for (n <- (1 to 10)) println(n)
|
|
404 |
|
|
405 |
|
199
|
406 |
// BTW: a roundabout way of printing out a list, say
|
|
407 |
val lst = ('a' to 'm').toList
|
140
|
408 |
|
202
|
409 |
for (n <- lst) println(n)
|
|
410 |
|
199
|
411 |
for (i <- (0 until lst.length)) println(lst(i))
|
|
412 |
|
200
|
413 |
// Why not just? Why making your life so complicated?
|
199
|
414 |
for (c <- lst) println(c)
|
|
415 |
|
|
416 |
// Aside: concurrency
|
|
417 |
// (ONLY WORKS OUT-OF-THE-BOX IN SCALA 2.11.8, not in SCALA 2.12)
|
|
418 |
// (would need to have this wrapped into a function, or
|
|
419 |
// REPL called with scala -Yrepl-class-based)
|
32
|
420 |
for (n <- (1 to 10)) println(n)
|
|
421 |
for (n <- (1 to 10).par) println(n)
|
|
422 |
|
|
423 |
|
36
|
424 |
// for measuring time
|
140
|
425 |
def time_needed[T](n: Int, code: => T) = {
|
32
|
426 |
val start = System.nanoTime()
|
140
|
427 |
for (i <- (0 to n)) code
|
32
|
428 |
val end = System.nanoTime()
|
140
|
429 |
(end - start) / 1.0e9
|
32
|
430 |
}
|
|
431 |
|
140
|
432 |
|
32
|
433 |
val list = (1 to 1000000).toList
|
|
434 |
time_needed(10, for (n <- list) yield n + 42)
|
|
435 |
time_needed(10, for (n <- list.par) yield n + 42)
|
|
436 |
|
|
437 |
|
140
|
438 |
|
200
|
439 |
// Just for "Fun": Mutable vs Immutable
|
|
440 |
//=======================================
|
|
441 |
//
|
|
442 |
// - no vars, no ++i, no +=
|
|
443 |
// - no mutable data-structures (no Arrays, no ListBuffers)
|
137
|
444 |
|
32
|
445 |
|
200
|
446 |
// Q: Count how many elements are in the intersections of two sets?
|
|
447 |
|
|
448 |
def count_intersection(A: Set[Int], B: Set[Int]) : Int = {
|
|
449 |
var count = 0
|
|
450 |
for (x <- A; if (B contains x)) count += 1
|
|
451 |
count
|
|
452 |
}
|
32
|
453 |
|
200
|
454 |
val A = (1 to 1000).toSet
|
|
455 |
val B = (1 to 1000 by 4).toSet
|
|
456 |
|
|
457 |
count_intersection(A, B)
|
|
458 |
|
|
459 |
// but do not try to add .par to the for-loop above
|
|
460 |
|
32
|
461 |
|
200
|
462 |
//propper parallel version
|
|
463 |
def count_intersection2(A: Set[Int], B: Set[Int]) : Int =
|
|
464 |
A.par.count(x => B contains x)
|
|
465 |
|
|
466 |
count_intersection2(A, B)
|
|
467 |
|
32
|
468 |
|
200
|
469 |
//for measuring time
|
|
470 |
def time_needed[T](n: Int, code: => T) = {
|
|
471 |
val start = System.nanoTime()
|
|
472 |
for (i <- (0 to n)) code
|
|
473 |
val end = System.nanoTime()
|
|
474 |
(end - start) / 1.0e9
|
|
475 |
}
|
|
476 |
|
|
477 |
val A = (1 to 1000000).toSet
|
|
478 |
val B = (1 to 1000000 by 4).toSet
|
|
479 |
|
|
480 |
time_needed(10, count_intersection(A, B))
|
|
481 |
time_needed(10, count_intersection2(A, B))
|
|
482 |
|
32
|
483 |
|
|
484 |
// Further Information
|
|
485 |
//=====================
|
|
486 |
|
200
|
487 |
// The Scala homepage and general information is at
|
32
|
488 |
//
|
|
489 |
// http://www.scala-lang.org
|
123
|
490 |
// http://docs.scala-lang.org
|
|
491 |
//
|
|
492 |
//
|
|
493 |
// It should be fairly easy to install the Scala binary and
|
200
|
494 |
// run Scala on the commandline. People also use Scala with
|
|
495 |
// Vim and Jedit. I currently settled on VS Code
|
123
|
496 |
//
|
200
|
497 |
// https://code.visualstudio.com
|
123
|
498 |
//
|
200
|
499 |
// There are also plugins for Eclipse and IntelliJ - YMMV.
|
|
500 |
// Finally there are online editors specifically designed for
|
|
501 |
// running Scala applications (but do not blame me if you lose
|
|
502 |
// all what you typed in):
|
123
|
503 |
//
|
200
|
504 |
// https://scalafiddle.io
|
|
505 |
// https://scastie.scala-lang.org
|
124
|
506 |
//
|
123
|
507 |
//
|
|
508 |
//
|
|
509 |
// Scala Library Docs
|
124
|
510 |
//====================
|
123
|
511 |
//
|
|
512 |
// http://www.scala-lang.org/api/current/
|
|
513 |
//
|
|
514 |
// Scala Tutorials
|
|
515 |
//
|
|
516 |
// http://docs.scala-lang.org/tutorials/
|
|
517 |
//
|
|
518 |
// There are also a massive number of Scala tutorials on youtube
|
200
|
519 |
// and there are tons of books and free material. Google is your
|
|
520 |
// friend.
|
32
|
521 |
|
|
522 |
|
170
|
523 |
|
|
524 |
|
|
525 |
|
|
526 |
|
|
527 |
|
|
528 |
|
|
529 |
|
195
|
530 |
|
|
531 |
|
|
532 |
|
|
533 |
|
|
534 |
|
|
535 |
|