tags:

views:

76

answers:

1

I've got a two dimensional array and I want to apply a function to each value in the array.

Here's what I'm working 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'm using foreach to extract the tuples:

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

Let's 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 runs, but need to apply to array(if mutable) or return new array.

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

Shouldn't be to bad. I'm missing some basics I think...

+4  A: 

(UPDATE: removed the for comprehension code which was not correct - 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 a 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)
IttayD
Given that the for comprehensions corresponds to `flatMap`/`map`, either it or the following example is incorrect.
Daniel
You're right. I removed the code
IttayD