[英]How does Groovy handle closure scope and recursion?
I have a recursive Python function that builds a tree, and I'm trying to translate it into Groovy. 我有一个递归的Python函数,它可以构建树,并且正在尝试将其转换为Groovy。
Here's the Python version... 这是Python版本...
def get_tree(vertices):
results = []
if type(vertices) != list:
vertices = [vertices]
for vertex in vertices:
results.append(vertex)
children = get_children(vertex)
if children:
child_tree = get_tree(children)
results.append(child_tree)
return results
Here's the output of get_tree(1)... 这是get_tree(1)的输出...
[1, [2, 3, 4, [5, 3]]]
And here's my attempt to translate this into a Groovy closure... 这是我尝试将其转换为Groovy闭包...
_tree = { vertices ->
results = []
vertices.each() {
results << it
children = it."$direction"().toList()
if (children) {
child_tree = _tree(children)
results << child_tree
}
}
results
}
But this doesn't work -- this is what it returns... 但这不起作用-这就是它的返回值...
gremlin> g.v(1).outTree()
==>[v[5], v[3], (this Collection), (this Collection)]
What are those "this Collection"s about? 这些“收藏”是关于什么的?
I have only a cursory understanding of Groovy, and I suspect it's something to do with how Groovy handles recursion and closure scope. 我对Groovy只是一个粗略的了解,我怀疑这与Groovy如何处理递归和关闭范围有关。
Please enlighten me :) 请赐教我:)
The solution was to add def
to results = []
: 解决方案是将
def
添加到results = []
:
_tree = { vertices ->
def results = []
vertices.each() {
results << it
children = it."$direction"().toList()
if (children) {
child_tree = _tree(children)
results << child_tree
}
}
results
}
See https://groups.google.com/d/msg/gremlin-users/iCPUifiU_wk/mrUhsjOM2h0J 请参阅https://groups.google.com/d/msg/gremlin-users/iCPUifiU_wk/mrUhsjOM2h0J
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.