Any SML coders able to translate this to Python?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Sep 7 08:59:46 EDT 2018
On Thu, 06 Sep 2018 13:48:54 +0300, Marko Rauhamaa wrote:
> Chris Angelico <rosuav at gmail.com>:
>> The request was to translate this into Python, not to slavishly imitate
>> every possible semantic difference even if it won't actually affect
>> behaviour.
>
> I trust Steven to be able to refactor the code into something more
> likable. His only tripping point was the meaning of the "let" construct.
Thanks for the vote of confidence :-)
However I have a follow up question. Why the "let" construct in the first
place? Is this just a matter of principle, "put everything in its own
scope as a matter of precautionary code hygiene"? Because I can't see any
advantage to the inner function:
>>>> def isqrt(n):
>>>> if n == 0:
>>>> return 0
>>>> else:
>>>> def f2398478957(r):
>>>> if n < (2*r+1)**2:
>>>> return 2*r
>>>> else:
>>>> return 2*r+1
>>>> return f2398478957(isqrt(n//4))
Sure, it ensures that r is in its own namespace. But why is that an
advantage in a function so small? Perhaps its a SML functional-
programming thing.
Putting aside the observation that recursion may not be the best way to
do this in Python, I don't think that the inner function is actually
needed. We can just write:
def isqrt(n):
if n == 0:
return 0
else:
r = isqrt(n//4)
if n < (2*r+1)**2:
return 2*r
else:
return 2*r+1
By the way I got this from this paper:
https://www.cs.uni-potsdam.de/ti/kreitz/PDF/03cucs-intsqrt.pdf
--
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson
More information about the Python-list
mailing list