Skip to content

Instantly share code, notes, and snippets.

@markehammons
Last active December 19, 2015 04:18
Show Gist options
  • Save markehammons/5896043 to your computer and use it in GitHub Desktop.
Save markehammons/5896043 to your computer and use it in GitHub Desktop.
An example of a memoization function and a timing function.
def memoize[T,U](fn: (T, T => U) => U) = {
var map = HashMap.empty[T,U]
def memoedFn(t: T): U = { map.getOrElseUpdate(t, fn(t, memoedFn)) }
memoedFn _
}
val memoedFib = memoize((i: Long, rec: Long => Long) => i match { case x @ (0|1) => x; case x => rec(x-1) + rec(x-2)})
def time(fn: => Unit) = {
val start = System.currentTimeMillis()
fn
System.currentTimeMillis() - start
}
time {
List(1,2,3) map (_ + 5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment