Skip to content

Instantly share code, notes, and snippets.

@charlag
Created December 22, 2017 13:57
Show Gist options
  • Save charlag/86c9277a94771b9cabefb4f943d1513f to your computer and use it in GitHub Desktop.
Save charlag/86c9277a94771b9cabefb4f943d1513f to your computer and use it in GitHub Desktop.
Simple memoization extension with capacity == 1.
package io.charlag.memoize
fun <A, E> ((A) -> E).memoize(): ((A) -> E) {
var arg: A? = null
var result: E? = null
return { a ->
if (a != arg) {
arg = a
result = this(a)
}
result!!
}
}
fun <A, B, E> ((A, B) -> E).memoize(): ((A, B) -> E) {
var arg: Pair<A,B>? = null
var result: E? = null
return { a, b ->
if (a != arg?.first || b != arg?.second) {
arg = a to b
result = this(a, b)
}
result!!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment