簡體   English   中英

新手在Groovy /遍歷樹中使用遞歸?

[英]Newbie on use of recursion in Groovy/traverse tree?

在我們當前的應用程序中,我們需要遍歷樹並捕獲特定設備(和子設備)上的所有操作員。 設備可以具有子設備,其上還具有特定的運營商。

由於我是Groovy中使用遞歸的新手,我想知道我是否正在做正確的事情......? 任何幫助我學習更好的做事方式的指針?

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()
}

有幾點需要注意:

  • 通過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()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM