Can an F# function be considered tail recursive it uses the TailCall .net opcode

做~自己de王妃 提交于 2019-12-01 18:26:41

See this blog post on the F# team blog for a summary of how F# compiles tail calls.

In short,

  1. Direct recursive tail calls are typically converted into loops.
  2. Mutual recursion and indirect non-recursive tail calls are typically turned into .NET tail calls.

but see the full post for all of the gory details.

Yes, if the compiler emits the tail call instruction, that call will be tail recursive (as of CLR 4, but there are still some exceptions, where it won't be actually tail recursive). But that doesn't necessarily mean that the whole function is tail recursive. For example, I can imagine QuickSort function compiled so that the first recursive call is not tail recursive and the second one is.

Also, just because some function does not contain the tail instruction, it doesn't necessarily mean that it is not tail recursive. The JIT compiler can recognize a tail call even without the tail instruction and optimize it as such.

What's more, the F# compiler sometimes compiles recursive functions in a non-recursive way. This is somewhat different than normal tail call optimization and the tail instruction is not used, but the overall effect is similar.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!