Skip to content

Instantly share code, notes, and snippets.

@zlangley
Last active August 29, 2015 14:02
Show Gist options
  • Save zlangley/7df11e3983b704058a39 to your computer and use it in GitHub Desktop.
Save zlangley/7df11e3983b704058a39 to your computer and use it in GitHub Desktop.
Memoize 1-parameter function.
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