0

(Still new to scala) I have a List[SortedSet[A]], and I'd like a unique SortedSet[A] with all (unique and sorted) elements. How should I do that?

My goal is: I have a class, say Container, that contain a list of Element and a list of (sub)Container. This class should implement a recursive getSortedElements(): SortedSet[Element] methods.

So I easily have this invalid code:

case class Container(myElements: List[Element], myContainers: List[Container]){
    def getSortedElements(): SortedSet[Element] =
        SortedSet(myElements) ++ SortedSet(myContainers.map(_.getSortedElements))
}
Juh_
  • 14,628
  • 8
  • 59
  • 92
  • Just to clarify, you want the output to be a `SortedSet` with all the items in ALL the `SortedSet`s in the `List`? – childofsoong Aug 03 '15 at 17:51
  • Yup. `List(SortedSet(3,5,7),SortedSet(2,5,8))` => `SortedSet(2,3,5,7,8)` but not with integers – Juh_ Aug 03 '15 at 17:56

1 Answers1

1

Scala's Set types already enforce uniqueness, so all you need to do is combine them:

val a = SortedSet(1,2,3)
val b = SortedSet(2,7,5)
val c = SortedSet(1, 9)
List(a, b, c).fold(SortedSet())((x, y) => x ++ y)

You can also use reduce instead of fold:

List(a, b, c).reduce((x, y) => x ++ y)

See Scala : fold vs foldLeft for more about the differences between those

Community
  • 1
  • 1
childofsoong
  • 1,918
  • 16
  • 23