--- a/progs/lecture1.scala Mon Nov 09 17:49:12 2020 +0000
+++ b/progs/lecture1.scala Sat Nov 14 00:40:47 2020 +0000
@@ -2,16 +2,19 @@
//=================
+
// Value assignments
// (their names should be lower case)
//====================================
+
val x = 42
val y = 3 + 4
val z = x / y
val x = 70
print(z)
+
// (you cannot reassign values: z = 9 will give an error)
//var z = 9
//z = 10
@@ -292,26 +295,29 @@
// For-Comprehensions (not For-Loops)
//====================================
-(1 to 10).toList
-for (n <- (1 to 10).toList) yield {
- square(n) + 1
+val lst = (1 to 10).toList
+for (n <- lst) yield n * n
+
+
+for (n <- lst) yield {
+ square(n) + double(n)
}
for (n <- (1 to 10).toList;
- m <- (1 to 10).toList) yield (m, n)
+ m <- (1 to 5).toList) yield (n, m, n * m)
// you can assign the result of a for-comprehension
// to a value
val mult_table =
for (n <- (1 to 10).toList;
- m <- (1 to 10).toList) yield m * n
+ m <- (1 to 10).toList) yield n * m
println(mult_table.mkString)
mult_table.sliding(10,10).mkString("\n")
-// the list/set/... can also be constructed in any
-// other way
+// for-comprehensions also work for other
+// collections
for (n <- Set(10,12,4,5,7,8,10)) yield n * n
@@ -319,17 +325,14 @@
n * n
}
-if (1 == 2) "a" else "b"
+// with if-predicates / filters
-// with if-predicates / filters
+if (1 == 2) "a" else "b"
for (n <- (1 to 3).toList;
m <- (1 to 3).toList;
if (n + m) % 2 == 0) yield (n, m)
-for (n <- (1 to 3).toList;
- m <- (1 to 3).toList;
- if ((((n + m) % 2 == 0)))) yield (n, m)
// with patterns
@@ -343,11 +346,31 @@
// general pattern of for-yield
// (yield can be several lines)
-for (p <- ...) yield {
+for (pat <- ...) yield {
// potentially complicated
// calculation of a result
}
+// For without yield
+//===================
+
+// with only a side-effect (no list is produced),
+// has no "yield"
+
+for (n <- (1 to 10).toList) println(n * n)
+
+for (n <- (1 to 10).toList) yield n * n
+
+// BTW: a roundabout way of printing out a list, say
+val lst = ('a' to 'm').toList
+
+for (i <- (0 until lst.length)) println(lst(i))
+
+// Why not just? Why making your life so complicated?
+for (c <- lst) println(c)
+
+
+
// Functions producing multiple outputs
//======================================
@@ -371,23 +394,6 @@
strs.maxBy(_._1)
-// For without yield
-//===================
-
-// with only a side-effect (no list is produced),
-// has no "yield"
-
-for (n <- (1 to 10)) println(n)
-
-(1 to 10).toList
-(1 until 10).toList
-// BTW: a roundabout way of printing out a list, say
-val lst = ('a' to 'm').toList
-
-for (i <- (0 until lst.length)) println(lst(i))
-
-// Why not just? Why making your life so complicated?
-for (c <- lst) println(c)