Memoize and trampoline
Two methods turn a closure into a better version of itself: memoize remembers what it computed, and trampoline turns a deep recursion into a loop.
A cached result
memo.groovy
def calls = 0
def square = { int n ->
calls++
n * n
}.memoize()
println square(4)
println square(4)
println square(5)
println calls
groovy memo.groovy
16
16
25
2
The counter reaches 2 after three calls, because the second call of 4 returned the cached value without running the body. memoizeAtMost(n) caches at most n results and memoizeAtLeast(n) starts with a cache of n entries; a closure with no arguments cannot be memoized.
Recursion without the stack
A recursive closure that calls itself directly grows the JVM stack and dies at a few thousand frames. trampoline() makes the recursive call return to a loop instead, and the closure below needs it: 20 factorial is still small, and a plain recursion of 100 000 would not survive.
trampoline.groovy
def factorial
factorial = { int n, BigDecimal acc = 1G ->
if (n <= 1) {
acc
} else {
factorial.trampoline(n - 1, acc * n)
}
}.trampoline()
println factorial(20)
println factorial(5)
groovy trampoline.groovy
2432902008176640000
120
The closure is declared first and assigned after, because the body names the variable that holds it. Inside the body the recursive call is factorial.trampoline(...), not factorial(...): that call is the one the trampoline intercepts.
Counting down without recursion
The same trick works for a loop written as a recursion, which is how a functional style stays safe on the JVM:
count.groovy
def countdown
countdown = { int n ->
if (n == 0) {
'liftoff'
} else {
countdown.trampoline(n - 1)
}
}.trampoline()
println countdown(100000)
groovy count.groovy
liftoff
One hundred thousand frames would overflow the stack of a direct recursion; the trampoline runs them as a loop and prints the last value.
Related
- Currying and composition: the other methods that return a closure.
- Concurrency with the JDK: the work a trampoline keeps on one thread.
Article author: Arthur Isaev