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