All Downloads are FREE. Search and download functionalities are using the official Maven repository.

arrow.meta.internal.memoization.kt Maven / Gradle / Ivy

There is a newer version: 1.6.3-alpha.2
Show newest version
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