How do LISPs or MLs implement tail-call optimization?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I can’t speak on the exact implementation details different compilers/interpreters, however generally speaking tail-call optimization operates like this:
Normally a function call involves something like this:
However when a function is in tail position, which pretty much means you are returning the result of the function you are about to call, you can be tricky and do
Note that #1 and #2 don’t actually involve any work, #3 can be tricky or simple depending on your implementation, and 4-7 don’t involve anything special from the function you are calling. Also note that all of this results in a 0 stack growth with respect to your call stack, so this allows for infinte recursion and generally speeding things up a little.
Also note that this kind of optimization can be applied not only to directly recursive functions, but co-recursive functions and in fact all calls that are in tail position.