scala 减少一组空集是否有效?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6986241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it valid to reduce on an empty set of sets?
提问by gladed
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)
[...]
回答by paradigmatic
Reduce (left and right) cannot be applied on an empty collection.
Reduce(左和右)不能应用于空集合。
Conceptually:
从概念上讲:
myCollection.reduce(f)
is similar to:
类似于:
myCollection.tail.fold( myCollection.head )( f )
Thus the collection must have at least one element.
因此集合必须至少有一个元素。
回答by soc
This should do what you want:
这应该做你想做的:
setOfSets.foldLeft(Set[String]())(_ union _)
Although I haven't understood the requirement to not specify an ordering.
虽然我不明白不指定排序的要求。
回答by Xavier Guihot
Starting Scala 2.9, most collections are now provided with the reduceOptionfunction (as an equivalent to reduce) which supports the case of empty sequences by returning an Optionof the result:
从 开始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)

