Skip to content

Instantly share code, notes, and snippets.

@ramn
Created April 30, 2013 22:01
Show Gist options
  • Save ramn/5492279 to your computer and use it in GitHub Desktop.
Save ramn/5492279 to your computer and use it in GitHub Desktop.
times function in Scala. Do something a certain number of times. Uses type class to choose between Unit and value returning behaviour. Examples: times(5) { print("hi ") } => Unit hi hi hi hi hi times(2) { "a" } => Seq("a", "a")
package object util {
object Times {
trait TimesDoer[-Value, Result] {
def times(n: Int)(f: => Value): Result
}
implicit object TimesUnit extends TimesDoer[Unit, Unit] {
def times(n: Int)(f: => Unit): Unit = for (_ <- 0 until n) f
}
object TimesDefault extends TimesDoer[Any, Seq[Any]] {
def times(n: Int)(f: => Any): Seq[Any] = for (_ <- 0 until n) yield f
}
}
import Times._
def times[Value, Result](n: Int)(f: => Value)(implicit timesDoer: TimesDoer[Value, Result] = TimesDefault) =
timesDoer.times(n)(f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment