开发者

List.transpose crashes when any element is longer than head element

开发者 https://www.devze.com 2023-02-11 21:56 出处:网络
As illustrated: scala> List(List(1, 2), List(3, 4), List(5, 6)) transpose res7: List[List[Int]] = List(List(1, 3, 5), List(2, 4, 6))

As illustrated:

scala> List(List(1, 2), List(3, 4), List(5, 6)) transpose
res7: List[List[Int]] = List(List(1, 3, 5), List(2, 4, 6))

scala> List(List(1, 2), List(3), List(5, 6)) transpose
res8: List[List[Int]] = List(List(1, 3, 5), List(2, 6))

scala> List(List(1, 2), List(3, 4, 7), List(5, 6)) transpose
java.lang.IndexOutOfBoundsException: 2
        at scala.collection.immutable.Vector.checkRangeConvert(Vector.scala:104)
.开发者_如何学JAVA..

Is this behaviour deliberate? If so, why?

EDIT: even though part of the question has been clarified, I'd still like to propose a version of this method (perhaps with a different name) that accepts irregular sizes.


Yes it's intentional. It fails fast to any attempt to use irregular sizes. Check out the bug report https://issues.scala-lang.org/browse/SI-3399. Also take a look at how to write a transpose for your case: Is there a safe way in Scala to transpose a List of unequal-length Lists?

It works in the old method. Where 7 is silently ignored whereas in the previous examples all numbers appeared the result. I guess this was undesirable:

scala> List.transpose(List(List(1, 2), List(3, 4, 7), List(5, 6)))
warning: there were 1 deprecation warnings; re-run with -deprecation for details
res4: List[List[Int]] = List(List(1, 3, 5), List(2, 4, 6))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号