Scala 中最优雅的重复循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5764049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:58:19  来源:igfitidea点击:

Most elegant repeat loop in Scala

scalaloopscoding-style

提问by Przemek

I'm looking for an equivalent of:

我正在寻找相当于:

for(_ <- 1 to n)
  some.code()

that would be shortest and most elegant. Isn't there in Scala anything similar to this?

那将是最短和最优雅的。Scala 中没有类似的东西吗?

rep(n)
  some.code()

This is one of the most common constructs after all.

毕竟,这是最常见的构造之一。

PS

聚苯乙烯

I know it's easy to implement rep, but I'm looking for something predefined.

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

回答by Daniel C. Sobral

1 to n foreach { _ => some.code() }

回答by kiritsuku

You can create a helper method

您可以创建一个辅助方法

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

and use it:

并使用它:

rep(5) { println("hi") }

Based on @J?rgs comment I have written such a times-method:

基于@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") }

Based on @DanGordon comments, I have written such a times-method:

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

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

// use it with
10.times { println("hi") }

回答by Landei

I would suggest something like this:

我会建议这样的事情:

List.fill(10)(println("hi"))

There are other ways, e.g.:

还有其他方法,例如:

(1 to 10).foreach(_ => println("hi"))

Thanks to Daniel S. for the correction.

感谢 Daniel S. 的更正。

回答by missingfaktor

With scalaz 6:

使用 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@36659c23

scala> res5.unsafePerformIO
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

[ Snippet copied from here.]

[从这里复制的片段]