1

I have a recursive Python function that builds a tree, and I'm trying to translate it into Groovy.

Here's the Python version...

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)...

  [1, [2, 3, 4, [5, 3]]]

And here's my attempt to translate this into a Groovy closure...

_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.

Please enlighten me :)

espeed
  • 4,754
  • 2
  • 39
  • 51
  • You haven't provided enough information to have a working example. For example, what data are you feeding to this method? You probably should start with a simpler example. – OverZealous Aug 21 '11 at 03:32
  • Initially both the Python and Groovy method are fed an database ID. In this case, the initial database ID is the number 1. The Python get_children method and the Groovy it."$direction"().toList() are returning a list of IDs relative to the parent -- in this specific case it's building a threaded comment tree. – espeed Aug 21 '11 at 04:43
  • I think what @OverZealous was getting at is that there is too much ambiguity in your example code to be able to provide help. You need to simplify this down to a concise example that can be executed in a stand-alone manner. At a minimum that would mean static example data and example code for all methods involved. – Rhysyngsun Aug 22 '11 at 15:34

1 Answers1

0

The solution was to add def to 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

espeed
  • 4,754
  • 2
  • 39
  • 51