Search code examples
listscalasetnestedseq

How to make a nested toSet in scala in an idiomatic way?


Is there a more idiomatic way to change a nested sequence of sequences into a nested set of sets?

def toNestedSet[T](tsss: Seq[Seq[Seq[T]]]): Set[Set[Set[T]]]  = 
   tsss.map(_.map(_.toSet).toSet).toSet

Is it possible to implement a function which would work with lists of any depth?


Solution

  • To address the second part of your question (processing a list of arbitrary depth), something like this would work (type erasure gets in the way a bit):

      def toNestedSet(ts: Seq[Any]): Set[Any] = {
        ts.foldLeft[Set[Any]](Set())((acc, b) => b match {
            case s: Seq[_] => acc + toNestedSet(s)
            case x => acc + x
        })
      } 
    

    Note: quick and dirty -- it works, but fairly easy to break :)

    Edit: The cast was redundant