Created
April 26, 2019 22:19
-
-
Save Jswizzy/8bcc7371de09ef45c6e72789aca58516 to your computer and use it in GitHub Desktop.
Caching results
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
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