gla*_*ded 10 collections reduce scala set
这不应该工作吗?
> 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)
[...]
Run Code Online (Sandbox Code Playgroud)
par*_*tic 21
Reduce(左和右)不能应用于空集合.
概念:
myCollection.reduce(f)
Run Code Online (Sandbox Code Playgroud)
类似于:
myCollection.tail.fold( myCollection.head )( f )
Run Code Online (Sandbox Code Playgroud)
因此,集合必须至少有一个元素.
soc*_*soc 12
这应该做你想要的:
setOfSets.foldLeft(Set[String]())(_ union _)
Run Code Online (Sandbox Code Playgroud)
虽然我没有理解不指定订购的要求.
从 开始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)
Run Code Online (Sandbox Code Playgroud)