Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.isDefinedAt for n-dimensional arrays in scala

Tags:

arrays

scala

Is there an elegant way to express

val a = Array.fill(2,10) {1}
def do_to_elt(i:Int,j:Int) {
    if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j))
}

in scala?

like image 820
Elazar Leibovich Avatar asked Nov 05 '22 21:11

Elazar Leibovich


1 Answers

I recommend that you not use arrays of arrays for 2D arrays, for three main reasons. First, it allows inconsistency: not all columns (or rows, take your pick) need to be the same size. Second, it is inefficient--you have to follow two pointers instead of one. Third, very few library functions exist that work transparently and usefully on arrays of arrays as 2D arrays.

Given these things, you should either use a library that supports 2D arrays, like scalala, or you should write your own. If you do the latter, among other things, this problem magically goes away.

So in terms of elegance: no, there isn't a way. But beyond that, the path you're starting on contains lots of inelegance; you would probably do best to step off of it quickly.

like image 140
Rex Kerr Avatar answered Nov 11 '22 14:11

Rex Kerr