How to apply a function to each tuple of a multidimensional array in Scala?

I have a two-dimensional array and I want to apply a function to every value in the array.

Here is what I work with:

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))) 

I use foreach to extract tuples:

 scala> array.foreach(i => i.foreach(j => println(i))) [Lscala.Tuple2;@11d559a [Lscala.Tuple2;@11d559a [Lscala.Tuple2;@df11d5 [Lscala.Tuple2;@df11d5 

Make a simple function:

 //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) 

This is done, but you need to apply to the array (if modified) or return a new array.

 scala> array.foreach(i => i.foreach(j => foo(j._1, j._2))) 

Should not be bad. I missed some basics that I think ...

+4
source share
2 answers

(UPDATE: the remote code for understanding, which was incorrect - it returned a one-dimensional array)

 def foo(t: (Int, Int)): (Int, Int) = (t._1 + 1, t._2 + 1) array.map{_.map{foo}} 

To apply to mutable array

 val array = ArrayBuffer.tabulate(2,2)((x,y) => (0,0)) for (sub <- array; (cell, i) <- sub.zipWithIndex) sub(i) = foo(cell._1, cell._2) 
+4
source
 2dArray.map(_.map(((_: Int).+(1) -> (_: Int).+(1)).tupled)) 

eg.

 scala> List[List[(Int, Int)]](List((1,3))).map(_.map(((_: Int).+(1) -> (_: Int).+(1)).tupled)) res123: List[List[(Int, Int)]] = List(List((2,4))) 

Point notation required for compulsory

0
source

All Articles