tags:

views:

275

answers:

4

I find myself writing code like this when I want to repeat some execution n times:

for (i <- 1 to n) { doSomething() }

I'm looking for a shorter syntax like this:

n.times(doSomething())

Does something like this exist in Scala already?

EDIT

I thought about using Range's foreach() method, but then the block needs to take a parameter which it never uses.

(1 to n).foreach(ignored => doSomething())
+6  A: 

The Range class has a foreach method on it that I think is just what you need. For example, this:

 0.to(5).foreach(println(_))

produced

0
1
2
3
4
5

sblundy
Alternatively: `7 to 11 foreach { println(_) }`
Randall Schulz
`0 to 5 foreach println` looks cleaner.
missingfaktor
Anybody up for a little golf?
Randall Schulz
+12  A: 

You could easily define one using Pimp My Library pattern.

scala> implicit def intWithTimes(n: Int) = new {        
     |   def times(f: => Unit) = 1 to n foreach {_ => f}
     | }
intWithTimes: (n: Int)java.lang.Object{def times(f: => Unit): Unit}

scala> 5 times {
     |   println("Hello World")
     | }
Hello World
Hello World
Hello World
Hello World
Hello World
missingfaktor
I would love to have "times" added to RichInt.
Joa Ebert
It was actually added (https://lampsvn.epfl.ch/trac/scala/changeset/18599/scala/trunk/src/library/scala/runtime/RichInt.scala), but shortly after removed (https://lampsvn.epfl.ch/trac/scala/changeset/18648/scala/trunk/src/library/scala/runtime/RichInt.scala). Quoth extempore: "It was the best of times... it was the reversion of times...". Adding stuff to the standard library can break existing code, it has to be done fairly cautiously.
retronym
@retronym Interesting, thanks for the history.
Craig P. Motlin
That is really interesting. Is 2.8 not already breaking backwards compatibility? I think in that case someone missed the opportunity to add such a method. It boils down to people writing that code over and over again because there is a usecase for it. You could just name it different like "5 iterationsOf x" or "5 repetitionsOf x".
Joa Ebert
Joa: you may google up much discussion, including this precise idea.
extempore
+4  A: 

I'm not aware of anything in the library. You can define a utility implicit conversion and class that you can import as needed.

class TimesRepeat(n:Int) {
  def timesRepeat(block: => Unit): Unit = (1 to n) foreach { i => block }
}
object TimesRepeat {
  implicit def toTimesRepeat(n:Int) = new TimesRepeat(n)
}

import TimesRepeat._

3.timesRepeat(println("foo"))

Rahul just posted a similar answer while I was writing this...

huynhjl
A: 

OOPS, Should we start a project like Apache Commons for Scala ?! Scala team shoud add these utilities in Scala kernal ! OMG,Scala dont repeat Java's pitfalls please!