Displaying 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 of foo
type Array[A]
to get Array[B]
through foo.map{f}
.
Is there a clean way of matching f
over bar:Array[Array[A]]
to get Array[Array[B]]
that preserves the structure of the array bar
while mapping all elements A
to elements of type B
?
In general, is there a way to match elements of arrays of arbitrary dimensions (i.e. not only 2D, but 3D, 4D, etc.).
source to share
You can display the map:
bar.map(_.map(f))
I doubt there is a type safe way to map arrays of arbitrary dimensions, since arrays of different dimensions have different types. But this is simple enough to keep the nested 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 "general map and addition operations on arbitrarily nested data structures". I haven't tested with help Array
, but it looks like it works with other data structures.
everywhere(f)(bam)
source to share