1,"b"->2,"c"->1)...">

Handling a collection of sets and returning a flat iteration

val input=Set(Set("a","b"),Set("b","c"))

I want it:

Map("a"->1,"b"->2,"c"->1)

What is the best functional approach for implementing such functions? Using the yield keyword results in nested Iterables:

output = for(firstlevel<-input) yield for(item<-firstlevel) yield item
+5
source share
3 answers

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 }
+8
source

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")  
}

?

+1

for-comprehension yield:

output = for{
    (set,idx) <- input.zipWithIndex
    item <- set
} yield (item -> idx)

The code in the last line can be simplified (but not what you want):

output = for{
    set <- input
    item <- set
} yield item
+1
source

All Articles