Groovy如何处理闭包范围和递归?

问题描述:

我有一个递归Python函数来构建一棵树,我试图将它翻译成Groovy。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

您没有提供足够的信息,有一个工作的例子。例如,您输入的数据是什么?你可能应该从一个更简单的例子开始。 – OverZealous

+0

最初,Python和Groovy方法都有一个数据库ID。在这种情况下,初始数据库ID是数字1. Python get_children方法和Groovy它“$ direction”()。toList()返回一个相对于父级的ID列表 - 在这个特定情况下它正在建立一个线程评论树。 – espeed

+0

我认为@OverZealous得到的是,你的示例代码中有太多含糊不清的地方能够提供帮助。您需要将其简化为一个可以以独立方式执行的简明示例。至少这意味着涉及所有方法的静态示例数据和示例代码。 – Rhysyngsun

解决的办法是增加defresults = []

_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