Last active
December 19, 2015 04:18
-
-
Save markehammons/5896043 to your computer and use it in GitHub Desktop.
An example of a memoization function and a timing function.
This file contains 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
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