Matthew Hoggan
Matthew Hoggan

Reputation: 7594

Scala way of merging tuples in a list using functional programming techniques

Say I have:

val list: List[(Long, Boolean)] = List((0, false), (0, true), (1, true), (1, true))

and in the end I want:

List((0, false), (1, true))

Where the "Merged" list "Groups By" _1 and then "logically and" the results.

I can do this with iteration but it seems like Scala and functional programming in general should be able to use a set of functions to perform this transformation.

Upvotes: 2

Views: 48

Answers (2)

OlivierBlanvillain
OlivierBlanvillain

Reputation: 7768

Use List#groupBy followed by a sequence of map/reduce operations:

scala> List((0, false), (0, true), (1, true), (1, true))
res0: List[(Int, Boolean)] =
  List((0,false), (0,true), (1,true), (1,true))

scala> .groupBy(_._1)
res1: scala.collection.immutable.Map[Int,List[(Int, Boolean)]] =
  Map(1 -> List((1,true), (1,true)), 0 -> List((0,false), (0,true)))

scala> .mapValues(_.map(_._2))
res2: scala.collection.immutable.Map[Int,List[Boolean]] =
  Map(1 -> List(true, true), 0 -> List(false, true))

scala> .mapValues(_.reduce(_ && _))
res3: scala.collection.immutable.Map[Int,Boolean] =
  Map(1 -> false, 0 -> true)

scala> .toList
res4: List[(Int, Boolean)] =
  List((1,false), (0,true))

Upvotes: 1

Tzach Zohar
Tzach Zohar

Reputation: 37822

val result = list.groupBy(_._1) // group by key
  .mapValues(_.map(_._2))       // remove keys from grouped values
  .mapValues(_.reduce(_ && _))  // reduce grouped values using &&

Upvotes: 3

Related Questions