在数组上执行循环操作的功能方法

Dan*_*iel 0 java functional-programming scala

我目前有一个Java程序,它执行以下操作:

  int nvars = 10;
  long vars[] = new long[nvars];
  for(int i = 0; i < nvars; i++) {
      vars[i] = someFunction(i);
      anotherFunction(vars[i]);
  }
Run Code Online (Sandbox Code Playgroud)

我将其转换为Scala代码并具有:

val nvars: Int = 10
val vars: Array[Long] = new Array[Long](nvars)

for ( i <- 0 to nvars-1 )
    vars(i) = someFunction(i)
    anotherFunction(vars(i))
}
Run Code Online (Sandbox Code Playgroud)

关于如何使这个(更多)功能的任何建议?

Sha*_*nds 7

Array伴侣对象中有许多有用的构造函数方法,例如,根据您的情况,您可以使用tabulate:

val nvars: Int = 10
val vars = Array.tabulate(nvars){ someFunction } // calls someFunction on the values 0 to nvars-1, and uses this to construct the array
vars foreach (anotherFunction) // calls anotherFunction on each entry in the array
Run Code Online (Sandbox Code Playgroud)

如果anotherFunction返回一个结果而不仅仅是一个"副作用"函数,你可以通过调用来捕获它map:

val vars2 = vars map (anotherFunction) // vars2 is a new array with the results computed from applying anotherFunction to each element of vars, which is left unchanged.
Run Code Online (Sandbox Code Playgroud)