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

commonMain.arrow.core.MemoizedDeepRecursiveFunction.kt Maven / Gradle / Ivy

There is a newer version: 2.0.1
Show newest version
package arrow.core

import arrow.atomic.Atomic
import arrow.atomic.updateAndGet
import kotlin.jvm.JvmInline
import kotlin.jvm.JvmOverloads

public interface MemoizationCache {
  public fun get(key: K): V?
  public fun set(key: K, value: V): V
}

@JvmInline
public value class AtomicMemoizationCache(
  private val cache: Atomic> = Atomic(emptyMap())
): MemoizationCache {
  override fun get(key: K): V? = cache.get()[key]
  override fun set(key: K, value: V): V = cache.updateAndGet { old ->
    if (key in old) old else old + (key to value)
  }.getValue(key)
}

/**
 * Defines a recursive **pure** function that:
 * - keeps its stack on the heap, which allows very deep recursive computations that do not use the actual call stack;
 * - memoizes every call, which means that the function is execute only once per argument.
 *
 * [MemoizedDeepRecursiveFunction] takes one parameter of type [T] and returns a result of type [R].
 * The [block] of code defines the body of a recursive function. In this block
 * [callRecursive][DeepRecursiveScope.callRecursive] function can be used to make a recursive call
 * to the declared function.
 */
@JvmOverloads
public fun  MemoizedDeepRecursiveFunction(
  cache: MemoizationCache = AtomicMemoizationCache(),
  block: suspend DeepRecursiveScope.(T) -> R
): DeepRecursiveFunction = DeepRecursiveFunction { x ->
  when (val v = cache.get(x)) {
    null -> cache.set(x, block(x))
    else -> v
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy