updated
authorChristian Urban <christian.urban@kcl.ac.uk>
Sun, 22 Nov 2020 03:45:22 +0000
changeset 364 f1a6fa599d26
parent 363 e5c1d69cffa4
child 365 fc118ee0fce4
updated
progs/lecture1.scala
progs/lecture2.scala
progs/lecture3.scala
--- a/progs/lecture1.scala	Wed Nov 18 01:54:39 2020 +0000
+++ b/progs/lecture1.scala	Sun Nov 22 03:45:22 2020 +0000
@@ -522,26 +522,3 @@
 // friend.
 
 
-
-
-
-// declarative 
-
-users.filter(_.email.endsWith("@gmail.com"))
-
-// imperative
-
-val result = ListBuffer[User]()
-for(user <- users) {
-    if(user.email.endsWith("@gmail.com")) {
-        result += user
-    }
-}
-result.toList
-
-
-
-
-
-
-
--- a/progs/lecture2.scala	Wed Nov 18 01:54:39 2020 +0000
+++ b/progs/lecture2.scala	Sun Nov 22 03:45:22 2020 +0000
@@ -357,41 +357,34 @@
 
 // Note the difference between map and Map
 
-val ascii = ('a' to 'z').map(c => (c, c.toInt)).toList
-
-val ascii_Map = ascii.toMap
+val m = Map(1 -> "one", 2 -> "two", 10 -> "many")
 
+List((1, "one"), (2, "two"), (10, "many")).toMap
 
-def factors(n: Int) : List[Int] =
-  (2 until n).toList.filter(n % _ == 0)
+m.get(1)
+m.get(4)
 
-var ls = (1 to 10).toList
-val facs = ls.map(n => (n, factors(n)))
+m.getOrElse(1, "")
+m.getOrElse(4, "")
 
-facs.find(_._1 == 4)
+val new_m = m + (10 -> "ten")
 
-// works for lists of pairs
-facs.toMap
+new_m.get(10)
+
+val m2 = for ((k, v) <- m) yield (k, v.toUpperCase)
 
 
-facs.toMap.get(40)
-facs.toMap.getOrElse(42, Nil)
-
-val facsMap = facs.toMap
-
-val facsMap0 = facsMap + (0 -> List(1,2,3,4,5))
-facsMap0.get(0)
-
-val facsMap2 = facsMap + (1 -> List(1,2,3,4,5))
-facsMap.get(1)
-facsMap2.get(1)
 
 // groupBy function on Maps
+val lst = List("one", "two", "three", "four", "five")
+lst.groupBy(_.head)
 
-val ls = List("one", "two", "three", "four", "five")
-ls.groupBy(_.length)
+lst.groupBy(_.length)
 
-ls.groupBy(_.length).get(5)
+lst.groupBy(_.length).get(3)
+
+val grps = lst.groupBy(_.length)
+grps.keySet
 
 
 
@@ -594,11 +587,12 @@
 //================
 
 
-def moves(xs: List[Int], n: Int) : List[List[Int]] = (xs, n) match {
-  case (Nil, _) => Nil
-  case (xs, 0) => Nil
-  case (x::xs, n) => (x::xs) :: moves(xs, n - 1)
-}
+def moves(xs: List[Int], n: Int) : List[List[Int]] = 
+ (xs, n) match {
+   case (Nil, _) => Nil
+   case (xs, 0) => Nil
+   case (x::xs, n) => (x::xs) :: moves(xs, n - 1)
+ }
 
 
 moves(List(5,1,0), 1)
--- a/progs/lecture3.scala	Wed Nov 18 01:54:39 2020 +0000
+++ b/progs/lecture3.scala	Sun Nov 22 03:45:22 2020 +0000
@@ -415,21 +415,3 @@
 // multiple functions making tail calls to each other. Well,
 // nothing is perfect. 
 
-
-
-
-
-
-
-
-
-
-//************
-// Either
-val either1 : Either[Exception,Int] = Right(1)
-val either2: Either[Exception, Int] = Right(2)
-
-for{
-  one <- either1
-  two <- either2
-} yield one + two