Search code examples
scalascala-collectionsbitset

Aggregation of BitSet collection data in Scala


I have a function f that returns a BitSet from two input parameters.
Given values list, I need to return a joined BitSet from the function f. For example, with a values List that has 3 elements List(10,20,30), the method should return as follows:

val l = List(100,200,300)
def shiftAndJoin(values:List[Int]) = {
  f(10, l(0)) ++
  f(20, l(1)) ++
  f(30, l(2))
}

The simple and intuitive solution might be iteration over values with index to aggregate the BitSet() collection variable like this. However, I guess there should be a better way than this (some way that does not use ++= operator).

var r = BitSet()
(values zipWithIndex).foreach { case (v, i) => 
   r ++= f(v, l(i)) 
}

Solution

  • If I understand you correctly, this one-liner should do it:

    values.zip(l).map{case (v, i) => f(v,i)}.reduce{ _ ++ _ }
    

    (Generate all the individual BitSets from the map, then join them with reduce)