开发者

Array.isDefinedAt for n-dimensional arrays in 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) &&开发者_高级运维amp; a(i).isDefinedAt(j)) f(a(i)(j))
}

in scala?


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.


You just need to check the array at index i with isDefinedAt if it exists:

def do_to_elt(i:Int, j:Int): Unit =
  if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j))

EDIT: Missed that part about the elegant solution as I focused on the error in the code before your edit.

Concerning elegance: no, per se there is no way to express it in a more elegant way. Some might tell you to use the pimp-my-library-Pattern to make it look more elegant but in fact it does not in this case.

If your only use case is to execute a function with an element of a multidimensional array when the indices are valid then this code does that and you should use it. You could generalize the method by changing the signature of to take the function to apply to the element and maybe a value if the indices are invalid like this:

def do_to_elt[A](i: Int, j: Int)(f: Int => A, g: => A = ()) = 
  if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j)) else g

but I would not change anything beyond this. This also does not look more elegant but widens your use case.

(Also: If you are working with arrays you mostly do that for performance reasons and in that case it might even be better to not use isDefinedAt but perform validity checks based on the length of the arrays.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜