什么是集合的非扁平 Scala 向量:(1 到 2).flatMap((1 到 3).toSet.subsets(_))?
What is the non-flattened Scala Vector of Sets: (1 to 2).flatMap((1 to 3).toSet.subsets(_))?
我可以看到 (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))
将 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
returns 一个 Iterator[Set[A]]
,toVector
将 Iterator
转换为嵌套的 Vector
。
我可以看到 (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))
将 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
returns 一个 Iterator[Set[A]]
,toVector
将 Iterator
转换为嵌套的 Vector
。