Is there a safe way in Scala to transpose a List of unequal-length Lists?

后端 未结 5 980
南方客
南方客 2020-12-03 11:37

Given the following List:

val l = List(List(1, 2, 3), List(4, 5), List(6, 7, 8))

If I try to transpose it, Scala will throw the following e

5条回答
  •  没有蜡笔的小新
    2020-12-03 12:18

    This is probably the cleanest:

    def transpose[T](l: List[List[T]]): List[List[T]] =
         l.flatMap(_.headOption) match {
             case Nil => Nil
             case head => head :: transpose(l.map(_.drop(1)))
         }
    

    or a modified version that is even more efficient:

    def transpose[T](l: List[List[T]]): List[List[T]] =
         l.flatMap(_.headOption) match {
             case Nil => Nil
             case head => head :: transpose(l.collect { case _ :: tail => tail })
         }
    

提交回复
热议问题