Groovy 2.1.9中的闭包递归 [英] Recursion with closures in Groovy 2.1.9
问题描述
我无法在Groovy 2.1.9中调用递归闭包
I am unable to call recursive closures in Groovy 2.1.9
def facRec = {long n->
return n>1 ? n * facRec(n - 1) : 1
}
我得到一个TypeMissmatch
I'm getting a TypeMissmatch
推荐答案
当定义闭包时,它不知道变量 facRec
,因为它尚未定义...
When the closure is being defined, it has no idea of the variable facRec
as it has not yet been defined...
您可以这样做:
You can do:
def facRec
facRec = {long n->
return n>1 ? n * facRec(n - 1) : 1
}
你 can 可以将内层封装到另一个闭包中,并调用内层闭包的所有者(尽管我倾向于做到上述内容,因为它更易于阅读):
To get around this, or you can wrap the inner into another closure and call the owner of that inner closure (though I would tend to do the above as it is easier to read):
def facRec = {long n->
{ -> n > 1 ? n * owner.call( n - 1 ) : 1 }()
}
应该注意的是,这两者都会因 n
的大值而失败,因为您将溢出堆栈。
It should be noted that both of these will fail for big values of n
as you will overflow the stack
您可以使用蹦床来解决这个问题:
You can use trampoline to get round this:
def facRec
facRec = { n, count = 1G ->
n > 1 ? facRec.trampoline( n - 1, count * n ) : count
}.trampoline()
这篇关于Groovy 2.1.9中的闭包递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!