Most elegant repeat loop in Scala

前端 未结 4 874
遇见更好的自我
遇见更好的自我 2021-02-01 01:56

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 si

相关标签:
4条回答
  • 2021-02-01 02:17

    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. ]

    0 讨论(0)
  • 2021-02-01 02:19

    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.

    0 讨论(0)
  • 2021-02-01 02:23
    1 to n foreach { _ => some.code() }
    
    0 讨论(0)
  • 2021-02-01 02:40

    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") }
    
    0 讨论(0)
提交回复
热议问题