Scala中最优雅的重复循环

Prz*_*mek 38 loops coding-style scala

我正在寻找相当于:

for(_ <- 1 to n)
  some.code()
Run Code Online (Sandbox Code Playgroud)

这将是最短和最优雅的.Scala中没有与此类似的东西吗?

rep(n)
  some.code()
Run Code Online (Sandbox Code Playgroud)

毕竟这是最常见的结构之一.

PS

我知道实现代表很容易,但我正在寻找预定义的东西.

Dan*_*ral 79

1 to n foreach { _ => some.code() }
Run Code Online (Sandbox Code Playgroud)

  • @benroth否.实际上,`for(_ < - 1到n)some.code()`在编译期间被_translated_转换为`1到n foreach {_ => some.code()}`. (4认同)
  • @Willem它创建一个类型为"Range"的序列.无论开始还是结束,`Range`都有一个恒定的内存大小.它存在性能问题,但它们比这更微妙. (4认同)
  • 我不相信那是优雅的.在调用foreach之前,1到n构造函数是否不创建序列?如果n = 65000,那么内存开销是多少? (2认同)

kir*_*uku 17

您可以创建一个帮助方法

def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n-1)(f) } }
Run Code Online (Sandbox Code Playgroud)

并使用它:

rep(5) { println("hi") }
Run Code Online (Sandbox Code Playgroud)

根据@Jörgs评论,我写了这样一个时间方法:

class Rep(n: Int) {
  def times[A](f: => A) { loop(f, n) }
  private def loop[A](f: => A, n: Int) { if (n > 0) { f; loop(f, n-1) } }
}
implicit def int2Rep(i: Int): Rep = new Rep(i)

// use it with
10.times { println("hi") }
Run Code Online (Sandbox Code Playgroud)

根据@DanGordon的评论,我写了这样一个时间方法:

implicit class Rep(n: Int) {
    def times[A](f: => A) { 1 to n foreach(_ => f) } 
}

// use it with
10.times { println("hi") }
Run Code Online (Sandbox Code Playgroud)

  • 当`n`很大时,得到堆栈溢出.就像这个网站被命名为:) (4认同)

Lan*_*dei 10

我会建议这样的事情:

List.fill(10)(println("hi"))
Run Code Online (Sandbox Code Playgroud)

还有其他方法,例如:

(1 to 10).foreach(_ => println("hi"))
Run Code Online (Sandbox Code Playgroud)

感谢Daniel S.的修正.


mis*_*tor 9

使用scalaz 6:

scala> import scalaz._; import Scalaz._; import effects._;
import scalaz._
import Scalaz._
import effects._

scala> 5 times "foo"
res0: java.lang.String = foofoofoofoofoo

scala> 5 times List(1,2)
res1: List[Int] = List(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)

scala> 5 times 10
res2: Int = 50

scala> 5 times ((x: Int) => x + 1).endo
res3: scalaz.Endo[Int] = <function1>

scala> res3(10)
res4: Int = 15

scala> 5 times putStrLn("Hello, World!")
res5: scalaz.effects.IO[Unit] = scalaz.effects.IO$$anon$2@36659c23

scala> res5.unsafePerformIO
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Run Code Online (Sandbox Code Playgroud)

[从这里复制的片段.]