progs/lecture1.scala
changeset 497 ef37fb04a343
parent 491 2a30c7dfe3ed
--- a/progs/lecture1.scala	Mon Nov 10 16:07:36 2025 +0000
+++ b/progs/lecture1.scala	Mon Nov 10 16:24:46 2025 +0000
@@ -1,9 +1,9 @@
 // Scala Lecture 1
 //=================
 
-println("Hello World")
 
-
+// Topics
+//--------
 // - List, Sets, Ints, Strings, ... 
 // - Value assignments (val vs var)
 // - How to define functions? (What is returned?)
@@ -11,7 +11,6 @@
 // - For-Comprehensions (guards, with/without yield)
 // - String-Interpolations
 //
-//
 
 
 
@@ -44,7 +43,6 @@
 // picking an element in a list
 val lst = List(1, 2, 3, 1)
 
-val lst = List(1, 2, 3, 1)
 
 val lst1 = 0 :: lst
 
@@ -74,7 +72,6 @@
 (1 to 10).toList
 (1 to 10).toList.toString
 
-(1 until 10).toList
 
 
 // Equality in Scala is structural
@@ -229,6 +226,8 @@
 }
 
 average(List(1,2,3,4,56))
+
+
 def incr(x: Int) : Int = x + 1
 def double(x: Int) : Int = x + x
 def square(x: Int) : Int = x * x
@@ -252,32 +251,24 @@
 
 
 
-
-def len(xs: List[Int]) : Int = xs match {
-   case Nil => 0
-   case x :: xs => 1 + len(xs)
-}
-
-len(List(1,2,3,4,1))
-
-
-
 // If-Conditionals
 //=================
 
-// - Scala used to not have a then-keyword
+// - Scala used to *not* have a then-keyword
 // - !!both if-else branches need to be present!!
 
 def fact(n: Int) : Int = 
   if (n == 0) 1 else n * fact(n - 1)
 
+fact(5)
+
 
 // Scala 3 introduced if-then-else - maybe people 
 // desperately needed it 
 def fact(n: Int) : Int = 
   if n == 0 then 1 else n * fact(n - 1)
 
-fact(5)
+
 fact(150)
 
 /* boolean operators
@@ -351,10 +342,7 @@
        m <- (1 to 10).toList) yield n * m
 
 println(mult_table.mkString(","))
-mult_table.sliding(10,10).toList.mkString(",")
-
-
-.mkString("\n")
+mult_table.sliding(10,10).toList.mkString("\n")
 
 // for-comprehensions also work for other
 // collections
@@ -362,7 +350,6 @@
 for (n <- Set(10,12,4,5,7,8,10)) yield n * n
 
 for (n <- (1 to 10)) yield {
-
   n * n  
 }
 
@@ -381,9 +368,9 @@
 
 val lst = List((1, 4), (2, 3), (3, 2), (4, 1))
 
-` yield m + n 
+for (p <- lst) yield p._1 + p._2 
 
-for (p <- lst) yield p._1 + p._2 
+for ((m, n) <- lst) yield m + n 
 
 
 // general pattern of for-yield 
@@ -400,9 +387,9 @@
 // with only a side-effect (no list is produced),
 // has no "yield"
 
-val xs = for (n <- (1 to 10).toList) yield println(n * n)
+val xs = for (n <- (1 to 10).toList) println(n * n)
 
-xs.tail
+xs.tail  // error
 
 val foo = for (n <- (1 to 10).toList) yield n * n
 
@@ -451,7 +438,7 @@
 
 
 // Aside: concurrency 
-// scala-cli --extra-jars scala-parallel-collections_3-1.0.4.jar 
+// scala --extra-jars scala-parallel-collections_3-1.2.0.jar 
 
 for (n <- (1 to 10)) println(n)
 
@@ -498,9 +485,9 @@
 def test() = {
   var cnt = 0
 
-  for(i <- (1 to 100_000)) cnt += 1
+  for(i <- (1 to 100_000).par) cnt += 1
 
-  println(s"Should be 100000: $cnt")
+  println(s"Should be 100_000: $cnt")
 }
 
 test()