Recursion 在Groovy/traverse树中使用递归的新手?
在我们当前的应用程序中,我们需要遍历树并捕获特定设备(和子设备)上的所有操作员。设备上可能有子设备,子设备上也有特定的操作员 由于我是Groovy中使用递归的新手,我想知道我做的事情是否正确。。? 有什么方法可以帮助我学习更好的做事方法吗Recursion 在Groovy/traverse树中使用递归的新手?,recursion,groovy,Recursion,Groovy,在我们当前的应用程序中,我们需要遍历树并捕获特定设备(和子设备)上的所有操作员。设备上可能有子设备,子设备上也有特定的操作员 由于我是Groovy中使用递归的新手,我想知道我做的事情是否正确。。? 有什么方法可以帮助我学习更好的做事方法吗 def listOperators(device) { // list with all operator id's def results = [] // closure to traverse down the tree
def listOperators(device) {
// list with all operator id's
def results = []
// closure to traverse down the tree
def getAllOperators = { aDevice->
if(aDevice) {
aDevice.operators.each { it ->
results << it.id
}
}
if (aDevice?.children) {
aDevice.children.each { child ->
results << owner.call(child)
}
}
}
// call the closure with the given device
getAllOperators(device)
// return list with unique results
return results.unique()
}
def列表操作员(设备){
//包含所有操作员id的列表
def结果=[]
//关闭以遍历树
def getAllOperators={aDevice->
国际单项体育联合会(副主席){
aDevice.operators.each{it->
结果
结果需要注意的几件事:
- 通过
owner
执行递归调用不是一个好主意。如果调用嵌套在另一个闭包中,owner
的定义会发生变化。这很容易出错,并且与仅使用名称相比没有任何优势。当闭包是局部变量时,将其声明和闭包定义拆分,以便使用名称在范围内。例如:
def getAllOperators
getAllOperators={…
- 您正在将运算符附加到递归闭包外部的结果列表中。但是,您也在将每个递归调用的结果附加到同一个列表中。可以将每个递归调用的结果附加到列表中,也可以存储每个递归调用的结果,但不能同时存储这两个结果
这里有一个更简单的选择:
def listOperators(device) {
def results = []
if (device) {
results += device.operators*.id
device.children?.each { child ->
results += listOperators(child)
}
}
results.unique()
}
有几件事需要注意:
- 通过
owner
执行递归调用不是一个好主意。如果调用嵌套在另一个闭包中,owner
的定义会发生变化。这很容易出错,并且与仅使用名称相比没有任何优势。当闭包是局部变量时,将其声明和闭包定义拆分,以便使用名称在范围内。例如:
def getAllOperators
getAllOperators={…
- 您正在将运算符附加到递归闭包外部的结果列表中。但是,您也在将每个递归调用的结果附加到同一个列表中。可以将每个递归调用的结果附加到列表中,也可以存储每个递归调用的结果,但不能同时存储这两个结果
这里有一个更简单的选择:
def listOperators(device) {
def results = []
if (device) {
results += device.operators*.id
device.children?.each { child ->
results += listOperators(child)
}
}
results.unique()
}