Tail recursion to while iteration in 2 easy steps

Mark Janssen dreamingforward at gmail.com
Wed Oct 2 17:05:17 EDT 2013


On Wed, Oct 2, 2013 at 1:23 PM, Alain Ketterlin <alain at unistra.fr> wrote:
> On 10/02/2013 08:59 PM, Mark Janssen wrote:
>>>>
>>>> def fact(n): return 1 if n <= 1 else n * fact(n-1)
>>>
>>> How do know that either "<=" or "*" didn't rebind the name "fact" to
>>> something else? I think that's the main reason why python cannot apply
>>> any procedural optimization
>>
>> It's called "operator precedence".
>
> Operator precedence is totally irrelevant here, you misunderstand what
> "bind" means.
>
> Imagine that you call fact(x) where x is an instance of the following class:
>
> class Strange:
>   ...
>   def __le__(dummy):
>     global fact
>     fact = someotherfun # this is "binding"
>     return false
>
> i.e., executing "n<=1" calls __le__, which rebinds the name "fact" to
> someting else. Then, there is no recursive call at all. At the time
> fact(x-1) is executed, "fact" is not the same function any more.
>
> You cannot prevent this in python.


No, but you can't prevent a lot of bad moves in python.  What you just
did there is a total bonehead ("strange"?) of an idea.

-- 
MarkJ
Tacoma, Washington



More information about the Python-list mailing list