Handling a collection of sets and returning a flat iteration
update: suggestion to use input.toSeq.flatten
insteadinput.toSeq flatMap { _.toSeq }
convert to one sequence of values ...
input.toSeq.flatten
... group values corresponding to ...
input.toSeq.flatten groupBy { identity }
... and count
input.toSeq.flatten groupBy { identity } mapValues { _.size }
Oh boy it's so ugly ...
input.foldLeft(Map[String,Int]())((m,s) =>
s.foldLeft(m)((n,t) => n + (t -> (1 + n.getOrElse(t,0)))))
[change]
The Collection-API is really needed to "merge" two cards (or I just did not notice it ???), for example
def merge[A,B](m1: Map[A,B], m2:Map[A,B])(f: (B,B)=>B):Map[A,B] =
m1.foldLeft(m2)((m,t) =>
m + (t._1 -> m.get(t._1).map(k => f(k,t._2)).getOrElse(t._2)))
- :
input.map(_.map(x => x -> 1).toMap).reduceLeft(merge(_,_)(_+_))
[Edit2]
def merge[A,B](m1: Map[A,B], m2:Map[A,B])(f: (B,B)=>B):Map[A,B] =
m1.keys ++ m2.keys map {k => k ->
List(m1.get(k), m2.get(k)).flatten.reduceLeft(f)} toMap
, Scala -Fu .
(o1,o2) match {
case (Some(x),Some(y)) => Some(f(x,y))
case (Some(x), _) => Some(x)
case (_, Some(y)) => Some(y)
case => error("crack in the time-space-continuum")
}
?