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

gladed picture gladed · Aug 8, 2011 · Viewed 16.6k times · Source

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

Answer

paradigmatic picture paradigmatic · Aug 8, 2011

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.