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