Whilst starting to learn lisp, I’ve come across the term tail-recursive. What does it mean exactly?
Whilst starting to learn lisp, I’ve come across the term tail-recursive . What does
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.
Consider a simple function that adds the first N natural numbers. (e.g.
sum(5) = 0 + 1 + 2 + 3 + 4 + 5 = 15).Here is a simple JavaScript implementation that uses recursion:
If you called
recsum(5), this is what the JavaScript interpreter would evaluate:Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum.
Here’s a tail-recursive version of the same function:
Here’s the sequence of events that would occur if you called
tailrecsum(5), (which would effectively betailrecsum(5, 0), because of the default second argument).In the tail-recursive case, with each evaluation of the recursive call, the
running_totalis updated.Note: The original answer used examples from Python. These have been changed to JavaScript, since Python interpreters don’t support tail call optimization. However, while tail call optimization is part of the ECMAScript 2015 spec, most JavaScript interpreters don’t support it.