diff -r 937c995b047a -r ff815ca0bbcf progs/lecture1.scala --- a/progs/lecture1.scala Wed Jul 04 14:48:05 2018 +0100 +++ b/progs/lecture1.scala Tue Jul 10 15:09:28 2018 +0100 @@ -51,7 +51,7 @@ // some alterative syntax for lists -1::2::3::Nil +1 :: 2 :: 3 :: Nil List(1, 2, 3) ::: List(4, 5, 6) // Printing/Strings @@ -126,13 +126,13 @@ val lyrics = "Sun dips down, the day has gone. \n" + "Witches, wolves and giants yawn. \n" + "Queen and dragon, troll and gnome: \n" + - "tired buddies head for home" + "tired buddies head for home." */ val lyrics = """Sun dips down, the day has gone. |Witches, wolves and giants yawn. |Queen and dragon, troll and gnome: - |tired buddies head for home""".stripMargin + |tired buddies head for home.""".stripMargin println(lyrics) @@ -171,6 +171,9 @@ // If-Conditionals //================= +// Scala does not have a then-keyword +// both if-else branches need to be presents + def fact(n: Int) : Int = if (n == 0) 1 else n * fact(n - 1) @@ -186,13 +189,13 @@ */ -def fact2(n: BigInt): BigInt = +def fact2(n: BigInt) : BigInt = if (n == 0) 1 else n * fact2(n - 1) fact2(150) -def fib(n: Int): Int = +def fib(n: Int) : Int = if (n == 0) 1 else if (n == 1) 1 else fib(n - 1) + fib(n - 2) @@ -252,6 +255,9 @@ mult_table.sliding(10,10).mkString("\n") +// the list can also be constructed in any other way +for (n <- List(10,12,4,5,7,8,10)) yield n * n + // with if-predicates @@ -270,6 +276,14 @@ for (p <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield p._1 + p._2 +// general pattern + +for (x <- ...) yield { + // potentially complicated + // calculation of a result +} + + // with only a side-effect (no list is produced), // has no "yield" @@ -278,9 +292,6 @@ - - - // concurrency (ONLY WORKS IN SCALA 2.11.8, not in SCALA 2.12) // (would need to have this wrapped into a function, or // REPL called with scala -Yrepl-class-based) @@ -303,7 +314,7 @@ // mutable vs immutable factorial -def fact_mu(n: Long): Long = { +def fact_mu(n: Long) : Long = { var result : Long = 1 var i = 1 while (i <= n) { @@ -326,8 +337,8 @@ } } -test().sum -println(l1.sum - l2.sum) +(for (i <- (1 to 10)) yield test().sum).sum + // Webpages //========== @@ -533,7 +544,7 @@ santa_state("(((((()))))".toList) santa_imutable("(((((()))))".toList) -def randomString(length: Int) = +def randomString(length: Int) : String = List.fill(length)((40 + scala.util.Random.nextInt(2)).toChar)