Skip to content

Commit

Permalink
Additional test to check memoization + docs
Browse files Browse the repository at this point in the history
  • Loading branch information
serras committed Jul 10, 2023
1 parent 959054c commit 4f06749
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ package arrow.core
import arrow.atomic.Atomic
import arrow.atomic.loop

/**
* 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.
*/
public fun <T, R> MemoizedDeepRecursiveFunction(
block: suspend DeepRecursiveScope<T, R>.(T) -> R
): DeepRecursiveFunction<T, R> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,22 @@ class MemoizationTest : StringSpec({
result shouldBe 5
runs shouldBe 1
}

"Recursive memoization, run twice should be memoized" {
var runs = 0
val memoizedDeepRecursiveFibonacci: DeepRecursiveFunction<Int, Int> =
MemoizedDeepRecursiveFunction { n ->
when (n) {
0 -> 0.also { runs++ }
1 -> 1
else -> callRecursive(n - 1) + callRecursive(n - 2)
}
}
val result1 = memoizedDeepRecursiveFibonacci(5)
val result2 = memoizedDeepRecursiveFibonacci(5)
result1 shouldBe result2
runs shouldBe 1
}
})

private fun consecSumResult(n: Int): Int = (n * (n + 1)) / 2

0 comments on commit 4f06749

Please sign in to comment.