1

I am fairly new to scala and to functional programming in general so this might be a silly question to some. Anyway, I tried to search online, read some tutorials and the book ScalaByExample but I haven't found/reached the part where I can answer my inqury.

Here's my problem:

I have several functions that has these forms:

def func1(A: Array[Array[DataType]], B: Array[Array[DataType]],
  fn: (DataType, DataType) => PotentiallyDifferentDataType): Array[Array[DataType]] = {
  // Do something in each element using fn   
}

def func2(A: Array[DataType], B: Array[DataType],
  fn: (DataType, DataType) => PotentiallyDifferentDataType) = {
  // Do something for each element using fn
}

What I want to do is create a function that accepts 1D or 2D arrays and perform element-wise operations on those arrays where the elements of those arrays might be boolean, int, float or double.

jtitusj
  • 3,046
  • 3
  • 24
  • 40
  • The [map](http://www.brunton-spall.co.uk/post/2011/12/02/map-map-and-flatmap-in-scala/) function is what you want.Also you should consider using [`List`s instead of `Array`s](http://stackoverflow.com/questions/2712877/difference-between-array-and-list-in-scala) – TeWu May 17 '16 at 14:05

1 Answers1

0

If you know that A and B (and their member arrays) have the same length:

def func1[T, U](A: Array[Array[T]], B: Array[Array[T]], fn: (T, T) => U):
    Array[Array[U]] =
  A.zip(B) map { case (a, b) => func2(a, b, fn) }

def func2[T, U](A: Array[T], B: Array[T], fn: (T, T) => U): Array[U] =
  A.zip(B) map { case (a, b) => fn(a, b) }
devkat
  • 1,624
  • 14
  • 15