progs/lecture1.scala
changeset 504 7653dd662db3
parent 497 ef37fb04a343
--- a/progs/lecture1.scala	Sun Nov 16 12:26:31 2025 +0000
+++ b/progs/lecture1.scala	Thu Nov 27 18:24:07 2025 +0000
@@ -1,6 +1,7 @@
 // Scala Lecture 1
 //=================
 
+print("Hello")
 
 // Topics
 //--------
@@ -69,7 +70,7 @@
 
 // ranges
 1 to 10
-(1 to 10).toList
+(1 to 100).toString
 (1 to 10).toList.toString
 
 
@@ -183,7 +184,7 @@
 val name : Int = "bob"
 
 // type errors
-math.sqrt("64")
+math.sqrt(64)
 
 // produces
 //
@@ -217,18 +218,22 @@
 //     ....
 //  }
 
+def incr(x: Int) : Int = x + 1
+incr(42)
+
+def add(x: Int, y: Int) : Int = x + y
+
+
 def average(ls: List[Int]) : Int = {
-  println(s"$ls")
   val s = ls.sum
   val l = ls.length
-  if (l == 0) 0 
-  else s / l
+  s / l
 }
 
-average(List(1,2,3,4,56))
+average(List(1,2,3,4))
 
 
-def incr(x: Int) : Int = x + 1
+
 def double(x: Int) : Int = x + x
 def square(x: Int) : Int = x * x
 
@@ -320,20 +325,25 @@
 // For-Comprehensions (not For-Loops)
 //====================================
 
-val lst = (1 to 10).toSet
-val result = for (n <- lst) yield {
+val lst = (1 to 10).toList
+for (n <- lst) yield {
   n * n 
 }
 
 println(result)
 
+def square(n: Int) = n * n
+def double(n: Int) = n + n
+
 for (n <- lst) yield { 
   square(n) + double(n)
 }
 
-for (n <- (1 to 10).toList; 
-     m <- (1 to 5).toList) yield (n, m)
+val foo = for (n <- (1 to 10).toList; 
+     m <- (1 to 5).toList;
+     if (n + m) % 2 == 0) yield (n, m)
 
+foo.head
 
 // you can assign the result of a for-comprehension
 // to a value
@@ -376,10 +386,12 @@
 // general pattern of for-yield 
 // (yield can be several lines)
 
+/*
 for (pat <- ...) yield {
   // potentially complicated
   // calculation of a result
 }
+*/
 
 // For without yield
 //===================
@@ -387,6 +399,8 @@
 // with only a side-effect (no list is produced),
 // has no "yield"
 
+for (n <- (1 to 10).toList) yield println(n * n)
+
 val xs = for (n <- (1 to 10).toList) println(n * n)
 
 xs.tail  // error
@@ -478,10 +492,12 @@
 // But what the heck....lets try to count to 1 Mio in parallel
 // 
 // requires
-// scala --extra-jars scala- parallel-collections_3-1.0.4.jar
+// scala --extra-jars scala-parallel-collections_3-1.2.0.jar
 
 import scala.collection.parallel.CollectionConverters._
 
+for (n <- (1 to 10).par) println(n)
+
 def test() = {
   var cnt = 0
 
@@ -552,8 +568,8 @@
 // you can also implement your own string interpolations
 
 extension (sc: StringContext) {
-    def i(args: Any*): String = s"\t${sc.s(args:_*)}\n"
-    def l(args: Any*): String = s"${sc.s(args:_*)}:\n"
+    def i(args: Any*): String = s"\t${sc.s(args*)}\n"
+    def l(args: Any*): String = s"${sc.s(args*)}:\n"
 }
 
 // this allows you to write things like