如何在 Scala 中表示矩形二维(或多维)数组数据结构?
也就是说,每一行都有相同的长度,在编译时验证,但尺寸是在运行时确定的?
Seq[Seq[A]]
具有所需的接口,但它允许用户提供“参差不齐”的数组,这可能导致运行时失败。
Seq[(A, A, A, A, A, A)]
(和类似的)确实验证了长度是否相同,但它也强制在编译时指定这个长度。
示例界面
这是我的意思的示例界面(当然,内部维度不必是元组;它可以指定为列表或其他类型):
// Function that takes a rectangular array
def processArray(arr : RectArray2D[Int]) = {
// do something that assumes all rows of RectArray are the same length
}
// Calling the function (OK)
println(processArray(RectArray2D(
( 0, 1, 2, 3),
(10, 11, 12, 13),
(20, 21, 22, 23)
)))
// Compile-time error
println(processArray(RectArray2D(
( 0, 1, 2, 3),
(10, 11, 12),
(20, 21, 22, 23, 24)
)))