对空集合进行约简是否有效?
这不应该起作用吗?
> 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)
[...]
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)
[...]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
减少(左和右)不能应用于空集合。
从概念上讲:
类似于:
因此集合必须至少有一个元素。
Reduce (left and right) cannot be applied on an empty collection.
Conceptually:
is similar to:
Thus the collection must have at least one element.
这应该可以满足您的要求:
虽然我不明白不指定顺序的要求。
This should do what you want:
Although I haven't understood the requirement to not specify an ordering.
从 Scala 2.9 开始,大多数集合现在都提供了
reduceOption
函数(相当于reduce
),它通过返回结果的Option
来支持空序列的情况:Starting
Scala 2.9
, most collections are now provided with thereduceOption
function (as an equivalent toreduce
) which supports the case of empty sequences by returning anOption
of the result: