Skip to content

Instantly share code, notes, and snippets.

@Jswizzy
Created April 26, 2019 22:19
Show Gist options
  • Save Jswizzy/8bcc7371de09ef45c6e72789aca58516 to your computer and use it in GitHub Desktop.
Save Jswizzy/8bcc7371de09ef45c6e72789aca58516 to your computer and use it in GitHub Desktop.
Caching results
import kotlin.reflect.KProperty
import kotlin.system.measureTimeMillis
class Memoize<T, R>(val fn: (T) -> R) {
private val cache = mutableMapOf<T, R>()
operator fun getValue(thisRef: Any?, property: KProperty<*>) =
{ arg: T -> cache.getOrPut(arg) { fn(arg) } }
}
val fib: (Int) -> Long by Memoize { n: Int ->
when (n) {
0, 1 -> 1L
else -> fib(n - 1) + fib(n - 2)
}
}
fun main() {
measureTimeMillis { fib(40) }.also(::println)
measureTimeMillis { fib(45) }.also(::println)
measureTimeMillis { fib(500) }.also(::println)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment