Search code examples
.netf#tail-recursiontail-call-optimization

What's some simple F# code that generates the .tail IL instruction?


I'd like to see the .tail IL instruction, but the simple recursive functions using tail calls that I've been writing are apparently optimized into loops. I'm actually guessing on this, as I'm not entirely sure what a loop looks like in Reflector. I definitely don't see any .tail opcodes though. I have "Generate tail calls" checked in my project's properties. I've also tried both Debug and Release builds in Reflector.

The code I used is from Programming F# by Chris Smith, page 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

Can anyone suggest some simple F# code which will indeed generate .tail?


Solution

  • Mutually recursive functions should:

    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)
    

    (have not tried it just now).

    EDIT

    See also

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