14

我想使用不可变索引多维数组。有意义的结构是 a Vectorof Vectors。

scala> val v = Vector[Vector[Int]](Vector[Int](1,2,3), Vector[Int](4,5,6), Vector[Int](7,8,9))
v: scala.collection.immutable.Vector[Vector[Int]] = Vector(Vector(1, 2, 3), Vector(4, 5, 6), Vector(7, 8, 9))

只需指定维度就可以创建一个空数组,就像使用Array.ofDim.

scala> a = Array.ofDim[Int](3,3)
a: Array[Array[Int]] = Array(Array(0, 0, 0), Array(0, 0, 0), Array(0, 0, 0))

但是,没有Vector.ofDim, 功能,我找不到等价物。

不可变对象是否有等价Array.ofDim物?如果不是,为什么不呢?

4

3 回答 3

20

每个标准集合类都有一个带有工厂方法的伴随对象,包括fill. 举例:

Vector.fill(3, 3)( 0 )

请参阅相关的 scaladoc

于 2012-10-12T22:21:34.873 回答
15

有一个名为的创建方法tabulate,可让您根据索引设置内容:

scala> Vector.tabulate(3,3){ (i,j) => 3*i+j+1 }
res0: scala.collection.immutable.Vector[scala.collection.immutable.Vector[Int]] =
Vector(Vector(1, 2, 3), Vector(4, 5, 6), Vector(7, 8, 9))

如果您只需要零(或其他一些常量),您可以使用fill

scala> Vector.fill(3,3)(0)
res1: scala.collection.immutable.Vector[scala.collection.immutable.Vector[Int]] =
Vector(Vector(0, 0, 0), Vector(0, 0, 0), Vector(0, 0, 0))
于 2012-10-12T22:24:13.687 回答
5

您可以使用fill

scala> Vector.fill( 3 )( Vector.fill(3)(0) )
res1: scala.collection.immutable.Vector[scala.collection.immutable.Vector[Int]] = 
        Vector(Vector(0, 0, 0), Vector(0, 0, 0), Vector(0, 0, 0))
于 2012-10-12T22:15:00.133 回答