Why doesn't infinite recursion hit a stack overflow exception in F#?

Your recursionTest function is tail recursive, which means all recursive calls occurs in the 'tail position' i.e. as the last action in the function. This means the F# compiler does not need to allocate a new stack frame for recursive calls, so no stack overflow occurs.

Tail recursion is a specific case of tail call, the tail call being to itself rather than some other function.


In general, F# emits the tailcall instruction that .NET honors:

http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.tailcall(v=vs.95).aspx

In some specific simple cases, like yours, F# rewrites programs that use recursion into equivalent programs using loops.


This is an example of tail call optimization and so the compiler is optimizing it into a simple loop. See this: https://devblogs.microsoft.com/fsharpteam/tail-calls-in-f/

Try something like this:

let rec recursionTest x =
    recursionTest x + recursionTest (x * 2)