【问题标题】:What is the non-flattened Scala Vector of Sets: (1 to 2).flatMap((1 to 3).toSet.subsets(_))?什么是集合的非展平 Scala 向量:(1 到 2).flatMap((1 到 3).toSet.subsets(_))?
【发布时间】:2019-11-11 03:29:15
【问题描述】:

我可以看到(1 to 2) 是一个范围。

scala> (1 to 2)
res20: scala.collection.immutable.Range.Inclusive = Range(1, 2)

我可以从这个迭代器中看到集合。

scala> (1 to 3).toSet.subsets
res0: Iterator[scala.collection.immutable.Set[Int]] = non-empty iterator

scala> (1 to 3).toSet.subsets.mkString("\n")
res1: String =
Set()
Set(1)
Set(2)
Set(3)
Set(1, 2)
Set(1, 3)
Set(2, 3)
Set(1, 2, 3)

最后,这是一个扁平化时的集合向量。不平的时候是什么?如何显示?

scala> (1 to 2).flatMap((1 to 3).toSet.subsets(_))
res19: scala.collection.immutable.IndexedSeq[scala.collection.immutable.Set[Int]] = Vector(Set(1), Set(2), Set(3), Set(1, 2), Set(1, 3), Set(2, 3))

【问题讨论】:

  • 如果你运行(1 to 2).map((1 to 3).toSet.subsets),你会得到IndexedSeq[Iterator[Set[Int]]] = Vector(<iterator>, <iterator>)

标签: scala flatmap


【解决方案1】:

flatMap 替换为map 将给出一个不同大小的子集的非扁平化列表:

(1 to 2).map((1 to 3).toSet.subsets(_).toVector)
// res1: scala.collection.immutable.IndexedSeq[Vector[scala.collection.immutable.Set[Int]]] = Vector(
//   Vector(Set(1), Set(2), Set(3)),
//   Vector(Set(1, 2), Set(1, 3), Set(2, 3))
// )

请注意,由于subsets 返回Iterator[Set[A]]toVectorIterators 转换为嵌套的Vectors。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2017-04-23
    相关资源
    最近更新 更多