Skip to content

Instantly share code, notes, and snippets.

@qingwei91
Created September 4, 2017 14:11
Show Gist options
  • Select an option

  • Save qingwei91/19a02b4ba8f2a959614f040dc51bbfc2 to your computer and use it in GitHub Desktop.

Select an option

Save qingwei91/19a02b4ba8f2a959614f040dc51bbfc2 to your computer and use it in GitHub Desktop.
// this is slow .....
def fib(i: Int): Int = i match {
case 0 => 0
case 1 => 1
case n => fib(n - 2) + fib(n - 1)
}
val cacheBackend = new CacheBackEnd[Int, Int]
def cachedFib(i: Int): Int = cache(fib)(cacheBackend)(i)
// alternatively, we can inline the logic
def cachedFib(i: Int): Int = cache {
case 0 => 0
case 1 => 1
case n => fib(n - 2) + fib(n - 1)
}(cacheBackend)(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment