Scala Collections

Download Scala Collections

Post on 05-Dec-2014




1 download

Embed Size (px)




<ul><li> 1. Scala CollectionsiBAT Session &gt; June 17 2011 &gt; Meetu Maltiar </li> <li> 2. An Examplepackage com.inphina.collections.personclass Person(val name: String, val age: Int) { }Somewhere in the code:val (minors, adults) = people partition (_.age &lt; 18)Three concepts: - Simple pattern matching - An Infix method call - A function value </li> <li> 3. The Scala Way Of Collectionsscala&gt; val ys = List(1, 2, 3)ys: List[Int] = List(1, 2, 3)scala&gt; val xs: Seq[Int] = ysxs: Seq[Int] = List(1, 2, 3)scala&gt; xs map (_ + 1)res0: Seq[Int] = List(2, 3, 4)scala&gt; ys map (_ + 1)res1: List[Int] = List(2, 3, 4) </li> <li> 4. Collection PropertiesObject-orientedGeneric: List[T], Map[K, V]optionally persistent: scala.collections.immutableHigher-order with methods like foreach, map, filteruniform return type principle: operations returncollections of same type as their left operand </li> <li> 5. The Uniform Return Type PrincipleBulk operations return collections of the same type (constructor) astheir left operand.scala&gt; val ys = List(1,2,3)ys: List[Int] = List(1, 2, 3)scala&gt; val xs: Seq[Int] = ysxs: Seq[Int] = List(1, 2, 3)scala&gt; xs map(_ + 1)res0: Seq[Int] = List(2, 3, 4)scala&gt; ys map(_ + 1)res1: List[Int] = List(2, 3, 4) </li> <li> 6. Using Collections: Map and Filterscala&gt; val xs = List(1, 2, 3)xs: List[Int] = List(1, 2, 3)scala&gt; val ys = xs map (x =&gt; x + 1)ys: List[Int] = List(2, 3, 4)scala&gt; val ys = xs map (_ + 1)ys: List[Int] = List(2, 3, 4)scala&gt; val zs = ys filter (_ % 2 == 0)zs: List[Int] = List(2 , 4)scala&gt; val as = ys map (0 to _)as: List[scala.collection.immutable.Range.Inclusive] =List(Range(0, 1), Range(0, 1, 2), Range(0, 1, 2, 3)) </li> <li> 7. Using Collections: flatMap and groupByscala&gt; val bs = as.flattenbs: List[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)scala&gt; val bs = ys flatMap (0 to _)bs: List[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)scala&gt; val fruit = Vector("apples", "oranges", "ananas")fruit: scala.collection.immutable.Vector[java.lang.String] =Vector(apples, oranges, ananas)scala&gt; fruit groupBy (_.head)res3:scala.collection.immutable.Map[Char,scala.collection.immutable.Vector[java.lang.String]] = Map(a -&gt; Vector(apples, ananas), o -&gt;Vector(oranges)) </li> <li> 8. Using Collections: For Notationscala&gt; for (x for (x for (x aString map (_.toUpper)res12: String = HELLO WORLD </li> <li> 10. Using Mapsscala&gt; val m = Map(1 -&gt; "ABC", 2 -&gt; "DEF", 3 -&gt; "GHI")m: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -&gt; ABC,2 -&gt; DEF, 3 -&gt; GHI)scala&gt; m(2)res10: java.lang.String = DEFscala&gt; m + (4 -&gt; "JKL")res11: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -&gt;ABC, 2 -&gt; DEF, 3 -&gt; GHI, 4 -&gt; JKL)scala&gt; m map {case (k, v) =&gt; (v, k)}res12: scala.collection.immutable.Map[java.lang.String,Int] = Map(ABC-&gt; 1, DEF -&gt; 2, GHI -&gt; 3) </li> <li> 11. Scala Collection HierarchyAll Collection classes are in scala.collection or one of its sub-packages mutable, immutable and genericRoot collections in the package scala.collection define thesame interface as immutable collections and mutablecollections add some modification operations to make itmutableThe generic package contains building block for implementingCollections. </li> <li> 12. Scala.Collection Hierarchy </li> <li> 13. Scala.Collection.Immutable </li> <li> 14. Scala.Collection.Mutable </li> <li> 15. Overview Of CollectionsTraversable Iterable Seq IndexedSeq LinearSeq mutable.Buffer Range Set SortedSet immutable.HashSet mutable.HashSet mutable.LinkedHashSet BitSet Map SortedMap immutable.HashMap mutable.HashMap mutable.LinkedHashMap </li> <li> 16. Commonality In collectionsAll classes are quite common. For instance, everykind of collection can be created by same uniformSyntax Traversable(1, 2, 3) Iterable("x", "y", "z") Map("x" -&gt; 24, "y" -&gt; 25, "z" -&gt; 26) Set(,, SortedSet("hello", "world") Buffer(x, y, z) IndexedSeq(1.0, 2.0) LinearSeq(a, b, c)The same principle applies with specific collection implementations List(1, 2, 3) HashMap("x" -&gt; 24, "y" -&gt; 25, "z" -&gt; 26) </li> <li> 17. Commonality In collections...All these Collections get displayed with toString in the same waythey are written aboveAll collections support the API provided by Traversable butspecializes types wherever it makes sensemap method in class Traversable returns another Traversable asits result. But this result type is overridden in subclasses scala&gt; List(1, 2, 3) map (_ + 1) res0: List[Int] = List(2, 3, 4) scala&gt; Set(1, 2, 3) map (_ * 2) res0: Set[Int] = Set(2, 4, 6)This behavior in the collections libraries is called the uniform return type principle. </li> <li> 18. Trait TraversableTop of collection hierarchy. Its abstract method is foreach:def foreach[U](f: Elem =&gt; U)Traversable also provides lot of concrete methods they fall infollowing categories Addition: ++, appends two traversables together Map operations: map, flatMap, and collect Conversions: toArray, toList, toIterable, toSeq, toIndexedSeq, toStream, toSet, toMap, Copying operations: copyToBuffer and copyToArray Size info operations: isEmpty, nonEmpty, size, and hasDefiniteSize Element retrieval operations: head, last, headOption, lastOption, and find Sub-Collection retrieval operations: tail, init, slice, take, drop, takeWhile, dropWhile, filter, filterNot, withFilter Subdivision operations: splitAt, span, partition, groupBy Element tests: exists, forall, count Folds: foldLeft, foldRight, /:, :, reduceLeft, reduceRight Specific Folds: sum, product, min, max String Operations: mkString, addString, stringPrefix </li> <li> 19. Trait IterableThis is the next Trait in Collection hierarchy. All methods in this traitare defined in terms of an abstract method iterator, which returnscollection results one by one.The foreach method from trait Traversable is implemented inIterable in terms of iteratordef foreach[U](f: Elem =&gt; U): Unit = { val it = iterator while (it.hasNext) f(} </li> <li> 20. An Example ..Task: Phone keys has mnemonics attached to themval mnemonics = Map( 2 -&gt; "ABC", 3 -&gt; "DEF", 4 -&gt; "GHI", 5 -&gt; "JKL", 6 -&gt; "MNO", 7 -&gt; "PQRS", 8 -&gt; "TUV", 9 -&gt; "WXYZ")Assume that you are given a dictionary dict as a list of words. Design aclass Coder with a method translate such that new Coder(dict).translate(phoneNumber)Produces all phrases of words which can serve as mnemonics for thephone numberExample The phone number 7225276257 should have a mnemonic Scala rocksas one element of the list of solution phrases </li> <li> 21. An ExampleCreating a mnemonics Mapval mnemonics = Map(2 -&gt; "ABC", 3 -&gt; "DEF", 4 -&gt; "GHI", 5 -&gt; "JKL",6 -&gt; "MNO", 7 -&gt; "PQRS", 8 -&gt; "TUV", 9 -&gt; "WXYZ")Creating reverse map with upper codeval upperCode: Map[Char, Char] = for ((digit, str) "5282"word.toUpperCase map (upperCode(_)) </li> <li> 22. Everything is a libraryCollections feel they are language constructsLanguage does not contain any collection relatedconstructs - no collection types - no collection literals - no collection operatorsEverything is in libraryThey are extensible </li> <li> 23. ConclusionDe-emphasize destructive updatesFocus on Transformers that map collections to collectionsHave complete range of persistent collections </li> <li> 24. Next StepsMaking and extending Scala CollectionParallel Collections:Move from Mutable Persistent Parallel </li> <li> 25. ReferencesMartin Oderskys talk at ParleysScala Collection documentation </li> </ul>