Array.isDefinedAt 用于 scala 中的 n 维数组
有没有优雅的表达方式?
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))
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议您不要将数组的数组用于二维数组,原因有三个。首先,它允许不一致:并非所有列(或行,随意选择)都需要具有相同的大小。其次,它效率低下——你必须遵循两个指针而不是一个。第三,很少有库函数可以透明且有效地处理作为 2D 数组的数组的数组。
鉴于这些情况,您应该使用支持 2D 数组的库,例如 scalala,或者您应该编写您的自己的。如果你做了后者,除其他外,这个问题就会神奇地消失。
所以就优雅而言:不,没有办法。但除此之外,你开始的道路还包含很多不优雅的地方;你可能最好尽快离开它。
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.
您只需要使用
isDefinedAt
检查索引i
处的数组是否存在:编辑: 错过了关于优雅解决方案的部分,因为我专注于编辑之前代码中的错误。
关于优雅:不,本身没有办法以更优雅的方式来表达它。有些人可能会告诉您使用 pimp-my-library-Pattern 使其看起来更优雅,但实际上在本例中并非如此。
如果您唯一的用例是在索引有效时使用多维数组的元素执行函数,那么此代码可以做到这一点,您应该使用它。您可以通过更改 的签名来概括该方法,以将函数应用于元素,如果索引无效,则可能是一个值,如下所示:
但我不会更改除此之外的任何内容。这看起来并没有更优雅,但拓宽了您的用例。
(另外:如果您使用数组,那么您这样做主要是出于性能原因,在这种情况下,最好不要使用
isDefinedAt
,而是根据数组的长度执行有效性检查.)You just need to check the array at index
i
withisDefinedAt
if it exists: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:
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.)