Is it valid to reduce on an empty set of sets?

こ雲淡風輕ζ 提交于 2019-12-05 17:43:01

问题


Shouldn't this work?

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

回答1:


Reduce (left and right) cannot be applied on an empty collection.

Conceptually:

myCollection.reduce(f)

is similar to:

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

Thus the collection must have at least one element.




回答2:


This should do what you want:

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

Although I haven't understood the requirement to not specify an ordering.




回答3:


Starting Scala 2.9, most collections are now provided with the reduceOption function (as an equivalent to reduce) which supports the case of empty sequences by returning an Option of the result:

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)


来源:https://stackoverflow.com/questions/6986241/is-it-valid-to-reduce-on-an-empty-set-of-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!