I want to work with an immutable indexed multidimensional array. The structure that makes sense is a Vector
of Vector
s.
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))
It would be nice to create an empty array just by specifying the dimensions, like you can with 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))
However, there is no Vector.ofDim
, function, and I can't find an equivalent.
Is there an equivalent of Array.ofDim
for immutable objects? If not, why not?
You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.
Scala has a method Array. ofDim to create a multidimensional array. This approach can be used to create arrays of up to five dimensions.
For a multidimensional array, memory for the elements of the array is required to be allocated contiguously. For a vector of vector, the memory for the elements is most likely going to be disjoint. Also, it is possible to defined a vector of vectors in which the number of columns is not same for each row.
Each standard collection class has a companion object with factory methods, including fill
. By example:
Vector.fill(3, 3)( 0 )
See the relevant scaladoc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With