December 2015
Intermediate to advanced
298 pages
5h 30m
English
Hark back a bit dear reader. If you recall, we had said that a Monoid needs to be associative and should have an identity value.
Instead of using groupBy and friends, we can instead think of the collections as monoids and use foldLeft. Here is an example of how we do this:
scala> val list = List("x" -> "y", "z" -> "c", "x" -> "p", "z" -> "d") // 1 list: List[(String, String)] = List((x,y), (z,c), (x,p), (z,d)) scala> Map[String, List[String]]() // 2 acc: scala.collection.immutable.Map[String,List[String]] = Map() scala> list.foldLeft(acc) { (a, b) => | a + (b._1 -> (b._2 :: a.getOrElse(b._1, Nil))) | } // 3 res0: scala.collection.immutable.Map[String,List[String]] = Map(x -> List(p, y), z -> List(d, c))
The salient points of the ...
Read now
Unlock full access