scala - 如何在 Scala 中创建多维向量?

标签 scala scala-collections

我想使用不可变索引多维数组。有意义的结构是 VectorVector 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))

只需指定维度就可以创建一个空数组,就像使用 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 的等价物?对于不可变对象(immutable对象)?如果不是,为什么不呢?

最佳答案

有一种创建方法叫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))

关于scala - 如何在 Scala 中创建多维向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12867480/

相关文章:

scala - 是否可以在 lichess.org 上保存派对分析

scala - 将列表转换为映射,其中键为 Scala 中的索引

java - 为什么类型参数绑定(bind) T < : Comparable[T] fail for T = Int?

scala - 如何修复 Scala (Akka 2.4.0) 中被逐出的库和不明确的引用错误?

file - 在 Scala 中查找与通配符字符串匹配的文件

ruby - Scala 中的干净异常处理

Scala SBT 如何同时运行测试和测试

scala - 查找两个日期 scala 之间的日期

scala - Aux 模式在 Scala 中完成了什么?

.net - 如何在 Windows Phone 上运行 Scala?