14

这不应该工作吗?

> 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)
  [...]
4

3 回答 3

22

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

从概念上讲:

myCollection.reduce(f)

类似于:

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

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

于 2011-08-08T17:51:12.713 回答
15

这应该做你想要的:

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

虽然我不明白不指定订购的要求。

于 2011-08-09T13:49:31.497 回答
8

从 开始Scala 2.9,大多数集合现在都提供了reduceOption函数(作为等效于reduce),它通过返回结果的 an 来支持空序列的情况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)
于 2018-10-02T00:08:20.960 回答