Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将函数应用于Scala中多维数组的每个元组?_Scala_Tuples - Fatal编程技术网

如何将函数应用于Scala中多维数组的每个元组?

如何将函数应用于Scala中多维数组的每个元组?,scala,tuples,Scala,Tuples,我有一个二维数组,我想对数组中的每个值应用一个函数 以下是我的工作内容: scala> val array = Array.tabulate(2,2)((x,y) => (0,0)) array: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,0)), Array((0,0), (0,0))) 我使用foreach提取元组: scala> array.foreach(i => i.foreach(j => pri

我有一个二维数组,我想对数组中的每个值应用一个函数

以下是我的工作内容:

scala> val array = Array.tabulate(2,2)((x,y) => (0,0))
array: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,0)), Array((0,0), (0,0)))
我使用foreach提取元组:

scala> array.foreach(i => i.foreach(j => println(i)))           
[Lscala.Tuple2;@11d559a
[Lscala.Tuple2;@11d559a
[Lscala.Tuple2;@df11d5
[Lscala.Tuple2;@df11d5
让我们做一个简单的函数:

//Takes two ints and return a Tuple2. Not sure this is the best approach.
scala> def foo(i: Int, j: Int):Tuple2[Int,Int] = (i+1,j+2)        
foo: (i: Int,j: Int)(Int, Int)
这将运行,但需要应用于数组(如果可变)或返回新数组

scala> array.foreach(i => i.foreach(j => foo(j._1, j._2)))
不应该太坏。我想我缺少了一些基础知识…

(更新:删除了不正确的for理解代码-它返回了一个一维数组)

应用于可变数组的步骤

val array = ArrayBuffer.tabulate(2,2)((x,y) => (0,0))
for (sub <- array; 
     (cell, i) <- sub.zipWithIndex) 
  sub(i) = foo(cell._1, cell._2)
val数组=数组缓冲表(2,2)((x,y)=>(0,0))
为(子)
e、 g


强制执行所需的点符号

鉴于for comprehensions对应于
flatMap
/
map
,它或以下示例不正确。
val array = ArrayBuffer.tabulate(2,2)((x,y) => (0,0))
for (sub <- array; 
     (cell, i) <- sub.zipWithIndex) 
  sub(i) = foo(cell._1, cell._2)
2dArray.map(_.map(((_: Int).+(1) -> (_: Int).+(1)).tupled))
scala> List[List[(Int, Int)]](List((1,3))).map(_.map(((_: Int).+(1) -> (_: Int).+(1)).tupled))
res123: List[List[(Int, Int)]] = List(List((2,4)))