What is the correct way to get a subarray in Scala?

ε祈祈猫儿з 提交于 2019-12-29 11:33:56

问题


I am trying to get a subarray in scala, and I am a little confused on what the proper way of doing it is. What I would like the most would be something like how you can do it in python:

x = [3, 2, 1]
x[0:2]

but I am fairly certain you cannot do this.

The most obvious way to do it would be to use the Java Arrays util library.

import java.util.Arrays
val start = Array(1, 2, 3)
Arrays.copyOfRange(start, 0, 2)

But it always makes me feel a little dirty to use Java libraries in Scala. The most "scalaic" way I found to do it would be

def main(args: List[String]) {
    val start = Array(1, 2, 3)
    arrayCopy(start, 0, 2)
}
def arrayCopy[A](arr: Array[A], start: Int, end: Int)(implicit manifest: Manifest[A]): Array[A] = {
    val ret = new Array(end - start)
    Array.copy(arr, start, ret, 0, end - start)
    ret
}

but is there a better way?


回答1:


You can call the slice method:

scala> Array("foo", "hoo", "goo", "ioo", "joo").slice(1, 4)
res6: Array[java.lang.String] = Array(hoo, goo, ioo)

It works like in python.




回答2:


Imagine you have an array with elements from a to f

scala> val array = ('a' to 'f').toArray // Array('a','b','c','d','e','f')

Then you can extract a sub-array from it in different ways:

  1. Dropping the first n first elements with drop(n: Int)

    array.drop(2) // Array('c','d','e','f')

  2. Take the first n elements with take(n: Int)

    array.take(4) // Array('a','b','c','d')

  3. Select any interval of elements with slice(from: Int, until: Int). Note that until is excluded.

    array.slice(2,4) // Array('c','d')

    The slice method is stricly equivalent to:
    array.take(4).drop(2) // Array('c','d')

  4. Exclude the last n elements with dropRight(n: Int):

    array.dropRight(4) // Array('a','b')

  5. Select the last n elements with takeRight(n: Int):

    array.takeRight(4) // Array('c','d','e','f')

Reference: Official documentation



来源:https://stackoverflow.com/questions/10830944/what-is-the-correct-way-to-get-a-subarray-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!