Created
May 17, 2019 15:55
-
-
Save latant/2a3f40658d3264dab606384d7ad9aeae to your computer and use it in GitHub Desktop.
Memoization in Kotlin
This file contains 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
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