Most elegant repeat loop in Scala

前端 未结 4 873
遇见更好的自我
遇见更好的自我 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] = 
    
    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. ]

提交回复
热议问题