documentation on Map.flatten声明如下:
Converts this map of traversable collections into a map formed by the elements of these traversable collections.
我得到“可遍历集合的 map ”。例如,这将是一个列表映射。仅根据该定义,
Map[Int, List[Int]]
会合格。但是什么是“由这些可遍历集合的元素形成的映射”?这听起来很简单,但我很难让它工作。
文档中提供的示例代码是......好吧......我们可以说,不适用吗?
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)
我尝试了一些不同的东西,但它们产生了相同的错误。下面是几个例子:
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
^
我错过了什么?
最佳答案
问题是编译器不“知道”如何解释您存储在 map 中的元素。也就是说,解释是不明显的,所以你必须提供你自己对元素的隐式 View 到一个可遍历的中。例如,对于您提供的案例,您希望解释类型 (Int, List[Int])
的 map 的每个元素。也许进入一个新的元组列表,其中第一个元素是原始元素键,值是给定键值中的每个值。在代码中:
implicit val flattener = (t: (Int,List[Int])) ⇒ t._2.map(x ⇒ (t._1, x))
val m = Map(1 → List(1, 2, 3), 2 → List(4, 5), 3 → List(6))
val fm = m.flatten
但是您必须自己提供“扁平化”功能。
关于Scala:Map.flatten 的用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29578300/