2013-05-09 78 views
1

不工作我已在下面的代碼段遞歸在常規

def normalFactorial = { BigInteger n -> 
n <= 1 ? 1 : normalFactorial(n - 1) * n 
} 

println normalFactorial(1) 
println normalFactorial(2) 

normalFactorial(1)方法,作爲預期工作正常和印刷品1。第二次調用失敗,出現以下異常。任何線索..?

May 09, 2013 10:39:23 PM org.codehaus.groovy.runtime.StackTraceUtils sanitize 

WARNING: Sanitizing stacktrace: 

groovy.lang.MissingMethodException: No signature of method: tailRecursion.normalFactorial() is applicable for argument types: (java.math.BigInteger) values: [1] 

    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55) 

回答

3

在定義閉合(如果是有道理的)的封閉是沒有定義

嘗試:

def normalFactorial 
normalFactorial = { BigInteger n -> 
    n <= 1 ? 1 : normalFactorial(n - 1) * n 
} 
+0

它的工作!。認爲閉包最終也會被編譯成一個java類中的方法。那麼爲什麼需要首先定義?只是想知道 – 2013-05-09 17:34:30

+0

因爲閉包不在其範圍內。第一種方法是有效的,因爲你沒有遞歸。 – Mark 2013-05-14 21:42:32