在Grails應用程序中,我試圖阻止在有向圖中創建循環。用戶能夠爲節點分配一個父節點,但是沒有節點應該是它自己的父節點的祖先。我寫了一個簡單的設置函數調用checkLineageForTarget,這是遞歸函數,做繁重:爲什麼這個Groovy閉包不會返回我期望的值?
boolean checkLineageForTarget(Integer target, Collection<Node>stillToProcess){
// true means that this is a safe addition
// false means that this addition creates a cycle
boolean retVal = stillToProcess.each {
Collection<Node> itsParents = getParentNodes(it)
if (it.id == target){
println("found a loop on " + target);
return false; // loop detected!
}
if (itsParents.empty){ return true; } // end of the line
return checkLineageForTarget(target, itsParents)
}
// at this point, retVal is always true, even when the "found a loop [...]" condition is met
return retVal;
}
這個「作品」,因爲它打印「發現了一個循環[...]」消息,但在閉包之外,retVal爲true,調用函數試圖添加新的父/子關係,並且我的堆棧運行。
我的誤解是什麼?
您可以用'.each'像那樣?我會使用'.every' – zoran119 2012-02-22 01:06:33
它是Grails,而不是「Groovy on Grails」 – 2012-02-22 01:35:41
@Burt哎呀,我的壞。 – 2012-02-22 16:02:51