Last active
August 29, 2015 14:02
-
-
Save zlangley/7df11e3983b704058a39 to your computer and use it in GitHub Desktop.
Memoize 1-parameter function.
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
def memoize[T, U](f: T => U) = { | |
val cache = scala.collection.mutable.HashMap[T, U]() | |
(t: T) => { | |
if (!cache.contains(t)) { | |
cache.put(t, f(t)) | |
} | |
cache.get(t).get | |
} | |
} | |
val fib: (Int => BigInt) = memoize { | |
n => if (n < 2) n else fib(n - 1) + fib(n - 2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment