Dimensions of a collection, and how to traverse it in an efficient, elegant manner

Posted by Bruce Ferguson on Stack Overflow See other posts from Stack Overflow or by Bruce Ferguson
Published on 2011-01-10T17:06:53Z Indexed on 2011/01/10 21:53 UTC
Read the original article Hit count: 139

I'm trying to find an elegant way to deal with multi-dimensional collections in Scala. My understanding is that I can have up to a 5 dimensional collection using tabulate, such as in the case of the following 2-Dimensional array:

val test = Array.tabulate[Double](row,col)(_+_)

and that I can access the elements of the array using

    for(i<-0 until row) {
       for(j<-0 until col) {
         test(i)(j) = 0.0
       }
    }

If I don't know a priori what I'm going to be handling, what might be a succinct way of determining the structure of the collection, and spanning it, without doing something like:

    case(Array(x)) =>
       for(i<-1 until dim1) {
          test(i) = 0.0
       }

    case(Array(x,y)) =>
       for(i<-1 until dim1) {
          for(j<-1 until dim2) {
              test(i)(j) = 0.0
          }
       }

    case(Array(x,y,z)) =>
    ...

The dimensional values n1, n2, n3, etc... are private, right? Also, would one use the same trick of unwrapping a 2-D array into a 1-D vector when dealing with n-Dimensional objects if I want a single case to handle the traversal?

Thanks in advance

Bruce

© Stack Overflow or respective owner

Related posts about scala

Related posts about multidimensional-array