2010-06-05 21 views
7

我希望看到.tail IL指令,但使用我一直在寫的tail調用的簡單遞歸函數顯然是優化成循環的。我實際上正在猜測,因爲我不完全確定Reflector中的循環是什麼樣的。儘管我確實沒有看到任何.tail操作碼。我在項目的屬性中選中了「生成尾部呼叫」。我也嘗試了反射器中的Debug和Release版本。什麼是生成.tail IL指令的一些簡單的F#代碼?

我使用的代碼是從Programming F# by Chris Smith,190頁:

let factorial x = 
// Keep track of both x and an accumulator value (acc) 
let rec tailRecursiveFactorial x acc = 
    if x <= 1 then 
     acc 
    else 
     tailRecursiveFactorial (x - 1) (acc * x) 
tailRecursiveFactorial x 1 

任何人都可以提出一些簡單的F#代碼這的確會產生.tail

回答

6

相互遞歸函數應該:

let rec even n = 
    if n = 0 then 
     true 
    else 
     odd (n-1) 
and odd n = 
    if n = 1 then 
     true 
    else 
     even (n-1) 

(還沒有嘗試過剛纔)。

編輯

參見

How do I know if a function is tail recursive in F#

+1

我剛纔檢查。是!它會生成.tail。 – 2010-06-05 07:37:15