我有一个构建树的递归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如何处理递归和闭包范围有关。
请赐教:)
答案 0 :(得分:0)
解决方案是将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