Skip to content

Instantly share code, notes, and snippets.

@espeed
Created August 25, 2011 04:49
Show Gist options
  • Save espeed/1170000 to your computer and use it in GitHub Desktop.
Save espeed/1170000 to your computer and use it in GitHub Desktop.
Groovy Trees
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 (correct) 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)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment