Last active
October 30, 2018 13:42
-
-
Save Mishkun/ec831cf29c9eff28d2e2096fd36b3364 to your computer and use it in GitHub Desktop.
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
class Memoize0<out R>(val f: () -> R) : () -> R { | |
private val value = lazy(f) | |
override fun invoke(): R { | |
return value | |
} | |
} | |
fun <R> memoize(block: () -> R): () -> R = Memoize0(block) | |
class Memoize1<in T, out R>(val f: (T) -> R) : (T) -> R { | |
private val values = mutableMapOf<T, R>() | |
override fun invoke(x: T): R { | |
return values.getOrPut(x, { f(x) }) | |
} | |
} | |
fun <T, R> memoize(block: (T) -> R): (T) -> R = Memoize1(block) | |
// Usage | |
val memoizedFoo = memoize { x: Int -> foo(x) } | |
val memoizedBar = memoize(::bar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment