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