arrow.meta.internal.memoization.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of arrow-meta Show documentation
Show all versions of arrow-meta Show documentation
Functional companion to Kotlin's Standard Library
package arrow.meta.internal
import java.util.concurrent.ConcurrentHashMap
fun ((P1) -> R).memoize(): (P1) -> R = object : (P1) -> R {
private val m = MemoizedHandler<((P1) -> R), MemoizeKey1, R>(this@memoize)
override fun invoke(p1: P1) = m(MemoizeKey1(p1))
}
private interface MemoizedCall {
operator fun invoke(f: F): R
}
private data class MemoizeKey1(val p1: P1) : MemoizedCall<(P1) -> R, R> {
override fun invoke(f: (P1) -> R) = f(p1)
}
private class MemoizedHandler, out R>(val f: F) {
private val m = Platform.newConcurrentMap()
operator fun invoke(k: K): R = m[k] ?: run { m.putSafely(k, k(f)) }
}
object Platform {
interface ConcurrentMap : MutableMap {
fun putSafely(k: K, v: V): V
}
fun newConcurrentMap(): ConcurrentMap {
val map by lazy { ConcurrentHashMap() }
return object : ConcurrentMap, MutableMap by map {
override fun putSafely(k: K, v: V): V =
map.putIfAbsent(k, v) ?: v
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy