Skip to content

Instantly share code, notes, and snippets.

@JorgeCastilloPrz
Last active March 2, 2018 08:53
Show Gist options
  • Save JorgeCastilloPrz/095527d3f97b14fbbf6065645b3295b9 to your computer and use it in GitHub Desktop.
Save JorgeCastilloPrz/095527d3f97b14fbbf6065645b3295b9 to your computer and use it in GitHub Desktop.
kotlinmemoize for a friend
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> ((T) -> R).memoize(): (T) -> R = Memoize1(this)
val memoizedSumFactors = { x: Int -> sumOfFactors(x) }.memoize()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment