progs/lecture2.scala
changeset 364 f1a6fa599d26
parent 363 e5c1d69cffa4
child 365 fc118ee0fce4
--- 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)