Mapping a function over a multidimensional array in scala

arrays, dictionary, multidimensional-array, scala

Solution

You can map within the map:

bar.map(_.map(f))

I doubt there's a type-safe way to map arrays of arbitrary dimensions, since arrays of different dimensions are of different types. But it's simple enough to keep nesting map calls:

scala> val bam = new Array[Array[Array[Array[Array[A]]]]](0)
bam: Array[Array[Array[Array[Array[A]]]]] = Array()

scala> bam.map(_.map(_.map(_.map(_.map(f)))))
res1: Array[Array[Array[Array[Array[B]]]]] = Array()

Actually, I found that shapeless has "generic map and fold operations over arbitrarily nested data structures". I haven't tested with `Array`, but it looks like it works with other data structures.

everywhere(f)(bam)

Problem

I know there is a clean way to map a function `f:A => B` over an array, `foo` of type `Array[A]` to get an `Array[B]` via `foo.map{f}`. Is there a clean way to map `f` over `bar:Array[Array[A]]` to get an `Array[Array[B]]` that preserves the array structure of `bar` while mapping all of the `A` elements to elements of type `B`? In general, is there a way to map the elements of arrays of arbitrary dimensions (i.e. not just 2D but 3D, 4D, etc.).

Original source