groovy伪递归优化

groovy伪递归优化
1、官网文档闭包这一章介绍了使用trampoline进行伪递归优化

def factorial
factorial = { int n, def accu = 1G ->
    if (n < 2) return accu
    factorial.trampoline(n - 1, n * accu)
}
factorial = factorial.trampoline()

assert factorial(1)    == 1
assert factorial(3)    == 1 * 2 * 3
assert factorial(1000) // == 402387260.. plus another 2560 digits

2、这里提供了另一种方式

def tco = {
    f -> {
        def value
        def active = false
        def accumulated = []
        def accumulator = {
            Object[] args ->{
                accumulated<
    if (n < 2)
        return accu
    factorial(n - 1, n * accu)
}
factorial = tco(factorial)
def res= factorial(3)
println res

你可能感兴趣的:(数据结构和算法,groovy)