Skip to content

Instantly share code, notes, and snippets.

@jdegoes
Created February 18, 2011 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jdegoes/834261 to your computer and use it in GitHub Desktop.
Save jdegoes/834261 to your computer and use it in GitHub Desktop.
object Util {
def BenchmarkCycles = 100000000
def time[Z](label: String)(f: => Z): Z = {
val startTime = System.currentTimeMillis
val result = f
val endTime = System.currentTimeMillis
println("Time for " + label + ": " + ((endTime - startTime) / 1000.0))
result
}
}
import Util._
object MaybeFunctions {
sealed trait Maybe[+T] {
def fold[Z](just: T => Z, nothing: => Z): Z
def filter(f: T => Boolean): Maybe[T] = fold[Maybe[T]](
just = t => if (f(t)) Just(t) else Zilch,
nothing = Zilch
)
def map[TT](f: T => TT): Maybe[TT] = fold(
just = t => Just(f(t)),
nothing = Zilch
)
def flatMap[TT](f: T => Maybe[TT]): Maybe[TT] = fold(
just = t => f(t),
nothing = Zilch
)
}
def Just[T](t: T): Maybe[T] = new Maybe[T] {
def fold[Z](just: T => Z, nothing: => Z) = just(t)
}
lazy val Zilch: Maybe[Nothing] = new Maybe[Nothing] {
def fold[Z](just: Nothing => Z, nothing: => Z) = nothing
}
def benchmark = {
time("functions") {
var i = 0
var maybe: Maybe[Int] = Just(4)
while (i < BenchmarkCycles) {
maybe = maybe.map(_ * 3).flatMap(j => Just(j * 2))
i = i + 1
}
}
}
}
object MaybeData {
sealed trait Maybe[+T] {
def filter(f: T => Boolean): Maybe[T] = this match {
case Just(t) if (f(t)) => Just(t)
case _ => Zilch
}
def map[TT](f: T => TT): Maybe[TT] = this match {
case Zilch => Zilch
case Just(t) => Just(f(t))
}
def flatMap[TT](f: T => Maybe[TT]): Maybe[TT] = this match {
case Zilch => Zilch
case Just(t) => f(t)
}
}
case class Just[T](t: T) extends Maybe[T]
case object Zilch extends Maybe[Nothing]
def benchmark = {
time("data") {
var i = 0
var maybe: Maybe[Int] = Just(4)
while (i < BenchmarkCycles) {
maybe = maybe.map(_ * 3).flatMap(j => Just(j * 2))
i = i + 1
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment