减少一组空集是否有效?

时间:2011-08-08 17:45:00

标签: scala collections set reduce

不应该这样吗?

> val setOfSets = Set[Set[String]]()    
setOfSets: scala.collection.immutable.Set[Set[String]] = Set()

> setOfSets reduce (_ union _)
java.lang.UnsupportedOperationException: empty.reduceLeft
  at scala.collection.TraversableOnce$class.reduceLeft(TraversableOnce.scala:152)
  [...]

3 个答案:

答案 0 :(得分:20)

Reduce(左和右)不能应用于空集合。

概念:

myCollection.reduce(f)

类似于:

myCollection.tail.fold( myCollection.head )( f )

因此集合必须至少有一个元素。

答案 1 :(得分:12)

这应该做你想要的:

setOfSets.foldLeft(Set[String]())(_ union _)

虽然我没有理解不指定订购的要求。

答案 2 :(得分:1)

Scala 2.9开始,现在大多数集合都提供了reduceOption函数(相当于reduce),该函数通过返回Option来支持空序列的情况。结果:

Set[Set[String]]().reduceOption(_ union _)
// Option[Set[String]] = None
Set[Set[String]]().reduceOption(_ union _).getOrElse(Set())
// Set[String] = Set()
Set(Set(1, 2, 3), Set(2, 3, 4), Set(5)).reduceOption(_ union _).getOrElse(Set())
// Set[Int] = Set(5, 1, 2, 3, 4)