O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

It is a Monoid

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required