Created
April 30, 2013 22:01
-
-
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")
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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