--- a/progs/lecture1.scala Fri Jan 19 14:09:08 2018 +0000
+++ b/progs/lecture1.scala Fri Feb 23 22:26:42 2018 +0000
@@ -302,9 +302,32 @@
time_needed(10, for (n <- list.par) yield n + 42)
-
+// mutable vs immutable factorial
+def fact_mu(n: Long): Long = {
+ var result : Long = 1
+ var i = 1
+ while (i <= n) {
+ result = result * i
+ i = i + 1
+ }
+ result
+}
+def fact_im(num: Long): Long = {
+ if (num == 1) num else
+ num * fact_im(num - 1)
+}
+def test() = {
+ for (i <- (0 to 10).par) yield {
+ val l1 = for (n <- (List.fill(100000)(20 to 21)).flatten.par) yield fact_mu(n)
+ val l2 = for (n <- (List.fill(100000)(20 to 21)).flatten.par) yield fact_im(n)
+ l1.sum - l2.sum
+ }
+}
+
+test().sum
+println(l1.sum - l2.sum)
// Webpages
//==========
@@ -456,3 +479,67 @@
//
+
+
+
+
+
+
+
+// advantage of case classes
+//
+case class Participant(name: String, score: Int, active: Boolean)
+
+val ps = Seq(Participant("Jack", 34, true),
+ Participant("Tom", 51, true),
+ Participant("Bob", 90, false))
+
+ps.filter(_.score < 50).
+ filter(_.active).
+ map(_.copy(active = false))
+
+
+
+// another example why state is bad...does not work yet
+
+// for measuring time
+def time_needed[T](n: Int, code: => T) = {
+ val start = System.nanoTime()
+ for (i <- (0 to n)) code
+ val end = System.nanoTime()
+ (end - start) / 1.0e9
+}
+
+def santa_state(plan: List[Char]) : Int = {
+
+ var floor = 0
+
+ for (i <- plan.par) {
+ if (i == '(') {
+ floor += 1
+ } else {
+ floor -= 1
+ }
+ }
+
+ floor
+}
+
+def i(c: Char) = if (c == '(') 1 else -1
+
+def santa_imutable(plan: List[Char]) : Int =
+ plan.par.map(i(_)).reduce(_ + _)
+
+santa_state("(((((()))))".toList)
+santa_imutable("(((((()))))".toList)
+
+def randomString(length: Int) =
+ List.fill(length)((40 + scala.util.Random.nextInt(2)).toChar)
+
+
+santa_state(randomString(100))
+
+val large_string = randomString(3000000)
+
+time_needed(10, santa_state(large_string))
+time_needed(10, santa_imutable(large_string))