Skip to content

Instantly share code, notes, and snippets.

@Mishkun
Last active October 30, 2018 13:42
Show Gist options
  • Save Mishkun/ec831cf29c9eff28d2e2096fd36b3364 to your computer and use it in GitHub Desktop.
Save Mishkun/ec831cf29c9eff28d2e2096fd36b3364 to your computer and use it in GitHub Desktop.
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