Skip to content

Instantly share code, notes, and snippets.

@latant
Created May 17, 2019 15:55
Show Gist options
  • Save latant/2a3f40658d3264dab606384d7ad9aeae to your computer and use it in GitHub Desktop.
Save latant/2a3f40658d3264dab606384d7ad9aeae to your computer and use it in GitHub Desktop.
Memoization in Kotlin
fun <A, R> memoize(function: (A) -> R): (A) -> R {
val results = mutableMapOf<A, R>()
return { arg -> results[arg] ?: function(arg).also { results[arg] = it } }
}
fun fib(n: Long): Long = if (n < 2) n else cfib(n - 1) + cfib(n - 2)
val cfib = memoize(::fib)
fun main() {
(1..50L).forEach { println(cfib(it)) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment