Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a function over a multidimensional array in scala

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

like image 941
dsg Avatar asked Nov 30 '25 05:11

dsg


1 Answers

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)
like image 62
leedm777 Avatar answered Dec 01 '25 18:12

leedm777



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!