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

后端 未结 5 977
南方客
南方客 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:30

    I don't know of (and can't imagine - isn't this is a bit odd?! [see discussion in comments]) a library function, but I can polish the code a little:

    scala> def transpose(x: List[List[Int]]): List[List[Int]] = {
         |   val b = new ListBuffer[List[Int]]
         |   var y = x filter (!_.isEmpty)
         |   while (!y.isEmpty) {
         |     b += y map (_.head)
         |     y = y map (_.tail) filter (!_.isEmpty)
         |   }
         |   b.toList
         | }
    

提交回复
热议问题