[英]How does Groovy handle closure scope and recursion?
我有一個遞歸的Python函數,它可以構建樹,並且正在嘗試將其轉換為Groovy。
這是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
這是get_tree(1)的輸出...
[1, [2, 3, 4, [5, 3]]]
這是我嘗試將其轉換為Groovy閉包...
_tree = { vertices ->
results = []
vertices.each() {
results << it
children = it."$direction"().toList()
if (children) {
child_tree = _tree(children)
results << child_tree
}
}
results
}
但這不起作用-這就是它的返回值...
gremlin> g.v(1).outTree()
==>[v[5], v[3], (this Collection), (this Collection)]
這些“收藏”是關於什么的?
我對Groovy只是一個粗略的了解,我懷疑這與Groovy如何處理遞歸和關閉范圍有關。
請賜教我:)
解決方案是將def
添加到results = []
:
_tree = { vertices ->
def results = []
vertices.each() {
results << it
children = it."$direction"().toList()
if (children) {
child_tree = _tree(children)
results << child_tree
}
}
results
}
請參閱https://groups.google.com/d/msg/gremlin-users/iCPUifiU_wk/mrUhsjOM2h0J
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.