Scala: Use for Map.flatten?

The documentation on Map.flatten states the following:

Converts this map of intersecting collections to a map formed by elements of these bypass collections.

I get a "workaround map". For example, it will be a map of lists. By this definition alone, a Map[Int, List[Int]] will qualify.

But what is a “map formed by elements of these workarounds”? It sounds simple, but it’s not easy for me to get it to work.

An example of the code given in the documentation ... well ... let's say, not applicable?

 val xs = List( Set(1, 2, 3), Set(1, 2, 3) ).flatten // xs == List(1, 2, 3, 1, 2, 3) val ys = Set( List(1, 2, 3), List(3, 2, 1) ).flatten // ys == Set(1, 2, 3) 

I tried several different things, but they give the same error. Here are some examples:

 scala> val m = Map(List(1) -> List(1,2,3), List(2) -> List(4,5,6), List(3) -> List(7,8,9)) m: scala.collection.immutable.Map[List[Int],List[Int]] = Map(List(1) -> List(1, 2, 3), List(2) -> List(4, 5, 6), List(3) -> List(7, 8, 9)) scala> m.flatten <console>:9: error: No implicit view available from (List[Int], List[Int]) => scala.collection.GenTraversableOnce[B]. m.flatten ^ scala> val m = Map(1 -> List(1,2,3), 2 -> List(4,5,6), 4 -> List(7,8,9)) m: scala.collection.immutable.Map[Int,List[Int]] = Map(1 -> List(1, 2, 3), 2 -> List(4, 5, 6), 4 -> List(7, 8, 9)) scala> m.flatten <console>:9: error: No implicit view available from (Int, List[Int]) => scala.collection.GenTraversableOnce[B]. m.flatten ^ 

What am I missing?

+6
source share
1 answer

The problem is that the compiler does not “know” how to interpret the elements stored on the map. That is, the interpretation is not obvious, so you must provide your own implicit representation of the elements in the passage. For example, for the case that you provide, you want to interpret each element of a map of type (Int, List[Int]) , possibly into a new list of tuples in which the first element is the source key of the element, and each value is the value of the originally set key value . In code:

 implicit val flattener = (t: (Int,List[Int])) ⇒ t._2.map(x ⇒ (t._1, x)) val m = Map(1List(1, 2, 3), 2List(4, 5), 3List(6)) val fm = m.flatten 

But you must provide the flattening function yourself.

+4
source

Source: https://habr.com/ru/post/984986/


All Articles