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

后端 未结 5 969
南方客
南方客 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 suspect the reason transpose is not defined on a "non-rectangular" list of lists is because mathematically the transpose operation is well-defined only on "rectangular structures". A desirable property of a transpose operation is that transpose( transpose(x) ) == x. This is not the case in your generalization of the transpose operation on non-rectangular list of lists.

    Also, take a look at my post on Transposing arbitrary collection-of-collections in Scala and think about doing it for non-rectangular collections-of-collections. You will end up with mathematically inconsistent definitions, leave alone implementations.

    I do agree that idiosyncratic "transpose" operations are often useful, but I also think that they should not be made available in standard libraries because of potential confusion regarding their precise definitions.

提交回复
热议问题