Python is not bad ;-)

Chris Angelico rosuav at gmail.com
Sat May 2 06:42:14 EDT 2015


On Sat, May 2, 2015 at 8:22 PM, Dave Angel <davea at davea.name> wrote:
> On 05/02/2015 05:58 AM, Marko Rauhamaa wrote:
>>>> Chris Angelico <rosuav at gmail.com>:
>>>>> Guido is against anything that disrupts tracebacks, and optimizing
>>> tail recursion while maintaining traceback integrity is rather harder.
>>>>>> Tail recursion could be suppressed during debugging. Optimized code can
>> play all kinds of non-obvious tricks with the execution frame.
>>>>> In the situations where it really is simple, you can always make the
>>> change in your own code anyway. Often, the process of converting
>>> recursion into tail recursion warps the code to the point where it's
>>> abusing recursion to implement iteration anyway, so just make it
>>> iterative.
>>>>>> While you shouldn't actively replace Python iteration with recursion, I
>> strongly disagree that naturally occurring tail recursion is abuse or
>> should be avoided in any manner.
>>>> When you strongly disagree, make sure you're disagreeing with what Chris
> actually said. The key phrase in his message was
> "converting recursion into tail recursion"
>> NOT "converting iteration into recursion"
> and NOT "naturally occurring tail recursion"

Indeed. I'll clarify my statement.
When a function needs to do further actions after the tail call, the
usual solution is to carry the information through parameters.
def stupid_sum_iter(x):
 """Calculate sum(range(x+1))"""
 tot = 0
 while x:
 tot += x
 x -= 1
 return tot
def stupid_sum_recur(x):
 return x and x + stupid_sum_recur(x - 1)
def stupid_sum_tail_recur(x, tot=0):
 if not x: return tot
 return stupid_sum_tail_recur(x - 1, tot + x)
Converting the recursive form into optimizable tail recursion requires
an accumulator parameter, which means it's virtually the same as the
iterative version. Naturally-occurring tail recursion does exist, but
it's far from all cases of recursion.
ChrisA


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /