Note that there are some explanatory texts on larger screens.

plurals
  1. POTransposing arbitrary collection-of-collections in Scala
    text
    copied!<p>I have to often transpose a "rectangular" collection-of-collections in Scala, e.g.: a list of maps, a map of lists, a map of maps, a set of lists, a map of sets etc. Since collections can be uniformly viewed as a mapping from a specific domain to a co-domain (e.g.: a List[A]/Array[A] is a mapping from the Int domain to the A co-domain, Set[A]is a mapping from the A domain to the Boolean co-domain etc.), I'd like to write a clean, generic function to do a transpose operation (e.g.: turn a map of lists to the transposed list of maps). However, I'm having trouble because other than the () operator, Scala doesn't seem to have a unified API to view collections abstractly as mappings ?</p> <p>So I end up writing a separate transpose for each type of collection-of-collections as follows:</p> <pre><code>def transposeMapOfLists[A,B]( mapOfLists: Map[A,List[B]] ) : List[Map[A,B]] = { val k = ( mapOfLists keys ) toList val l = ( k map { mapOfLists(_) } ) transpose; l map { v =&gt; ( k zip v ) toMap } } def transposeListOfMaps[A,B]( listOfMaps: List[Map[A,B]]) : Map[A,List[B]] = { val k = ( listOfMaps(0) keys ) toList val l = ( listOfMaps map { m =&gt; k map { m(_) } } ) transpose; ( k zip l ) toMap } def transposeMapOfMaps[A,B,C]( mapOfMaps: Map[A,Map[B,C]] ) : Map[B,Map[A,C]] = { val k = ( mapOfMaps keys ) toList val listOfMaps = k map { mapOfMaps(_) } val mapOfLists = transposeListOfMaps( listOfMaps ) mapOfLists map { p =&gt; ( p._1, ( k zip p._2 ) toMap ) } } </code></pre> <p>Can someone help me unify these methods into one generic collection-of-collections transpose ? It will also help me (and I am sure others) learn some useful Scala features in the process.</p> <p>ps: I have ignored exception handling and have assumed the input collection-of-collections is rectangular, i.e., all of the inner collections' domain elements constitute the same set.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload