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
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 })
}