updated
authorChristian Urban <urbanc@in.tum.de>
Thu, 17 Nov 2016 03:38:53 +0000
changeset 56 6fa91be92d0c
parent 55 6610c1dfa8a9
child 57 9b88f9e04344
updated
progs/lecture2.scala
--- a/progs/lecture2.scala	Thu Nov 17 03:10:44 2016 +0000
+++ b/progs/lecture2.scala	Thu Nov 17 03:38:53 2016 +0000
@@ -279,6 +279,34 @@
 sum_cubes(lst)
 
 
+
+// Avoid being mutable
+//=====================
+
+// a student showed me...
+import scala.collection.mutable.ListBuffer
+
+def collatz_max(bnd: Long): (Long, Long) = {
+  val colNos = ListBuffer[(Long, Long)]()
+  for (i <- (1L to bnd).toList) colNos += ((collatz(i), i))
+  colNos.max
+}
+
+def collatz_max(bnd: Long): (Long, Long) = {
+  (1L to bnd).map((i) => (collatz(i), i)).maxBy(_._1)
+}
+
+//views -> lazy collection
+def collatz_max(bnd: Long): (Long, Long) = {
+  (1L to bnd).view.map((i) => (collatz(i), i)).maxBy(_._1)
+}
+
+// raises a GC exception
+(1 to 1000000000).filter(_ % 2 == 0).take(10).toList
+// ==> java.lang.OutOfMemoryError: GC overhead limit exceeded
+
+(1 to 1000000000).view.filter(_ % 2 == 0).take(10).toList
+
 // Sudoku
 //========