progs/lecture2.scala
changeset 364 f1a6fa599d26
parent 363 e5c1d69cffa4
child 365 fc118ee0fce4
equal deleted inserted replaced
363:e5c1d69cffa4 364:f1a6fa599d26
   355 // Map type (upper-case)
   355 // Map type (upper-case)
   356 //=======================
   356 //=======================
   357 
   357 
   358 // Note the difference between map and Map
   358 // Note the difference between map and Map
   359 
   359 
   360 val ascii = ('a' to 'z').map(c => (c, c.toInt)).toList
   360 val m = Map(1 -> "one", 2 -> "two", 10 -> "many")
   361 
   361 
   362 val ascii_Map = ascii.toMap
   362 List((1, "one"), (2, "two"), (10, "many")).toMap
   363 
   363 
   364 
   364 m.get(1)
   365 def factors(n: Int) : List[Int] =
   365 m.get(4)
   366   (2 until n).toList.filter(n % _ == 0)
   366 
   367 
   367 m.getOrElse(1, "")
   368 var ls = (1 to 10).toList
   368 m.getOrElse(4, "")
   369 val facs = ls.map(n => (n, factors(n)))
   369 
   370 
   370 val new_m = m + (10 -> "ten")
   371 facs.find(_._1 == 4)
   371 
   372 
   372 new_m.get(10)
   373 // works for lists of pairs
   373 
   374 facs.toMap
   374 val m2 = for ((k, v) <- m) yield (k, v.toUpperCase)
   375 
   375 
   376 
   376 
   377 facs.toMap.get(40)
       
   378 facs.toMap.getOrElse(42, Nil)
       
   379 
       
   380 val facsMap = facs.toMap
       
   381 
       
   382 val facsMap0 = facsMap + (0 -> List(1,2,3,4,5))
       
   383 facsMap0.get(0)
       
   384 
       
   385 val facsMap2 = facsMap + (1 -> List(1,2,3,4,5))
       
   386 facsMap.get(1)
       
   387 facsMap2.get(1)
       
   388 
   377 
   389 // groupBy function on Maps
   378 // groupBy function on Maps
   390 
   379 val lst = List("one", "two", "three", "four", "five")
   391 val ls = List("one", "two", "three", "four", "five")
   380 lst.groupBy(_.head)
   392 ls.groupBy(_.length)
   381 
   393 
   382 lst.groupBy(_.length)
   394 ls.groupBy(_.length).get(5)
   383 
       
   384 lst.groupBy(_.length).get(3)
       
   385 
       
   386 val grps = lst.groupBy(_.length)
       
   387 grps.keySet
   395 
   388 
   396 
   389 
   397 
   390 
   398 
   391 
   399 // Pattern Matching
   392 // Pattern Matching
   592 
   585 
   593 // Jumping Towers
   586 // Jumping Towers
   594 //================
   587 //================
   595 
   588 
   596 
   589 
   597 def moves(xs: List[Int], n: Int) : List[List[Int]] = (xs, n) match {
   590 def moves(xs: List[Int], n: Int) : List[List[Int]] = 
   598   case (Nil, _) => Nil
   591  (xs, n) match {
   599   case (xs, 0) => Nil
   592    case (Nil, _) => Nil
   600   case (x::xs, n) => (x::xs) :: moves(xs, n - 1)
   593    case (xs, 0) => Nil
   601 }
   594    case (x::xs, n) => (x::xs) :: moves(xs, n - 1)
       
   595  }
   602 
   596 
   603 
   597 
   604 moves(List(5,1,0), 1)
   598 moves(List(5,1,0), 1)
   605 moves(List(5,1,0), 2)
   599 moves(List(5,1,0), 2)
   606 moves(List(5,1,0), 5)
   600 moves(List(5,1,0), 5)