Created
December 22, 2017 13:57
-
-
Save charlag/86c9277a94771b9cabefb4f943d1513f to your computer and use it in GitHub Desktop.
Simple memoization extension with capacity == 1.
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
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