Most elegant repeat loop in Scala
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?
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 开发者_如何学JAVApredefined.
1 to n foreach { _ => some.code() }
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:
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:
implicit class Rep(n: Int) {
def times[A](f: => A) { 1 to n foreach(_ => f) }
}
// use it with
10.times { println("hi") }
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.
With 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!
[ Snippet copied from here. ]
精彩评论