[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Any SML coders able to translate this to Python?

On 2018-09-04 14:26, Steven D'Aprano wrote:
> I have this snippet of SML code which I'm trying to translate to Python:
> fun isqrt n = if n=0 then 0
>              else let val r = isqrt (n/4)
>                   in
>                     if n < (2*r+1)^2 then 2*r
>                     else 2*r+1
>                   end
> I've tried reading up on SML and can't make heads or tails of the 
> "let...in...end" construct.

I don't know SML specifically, but my guess would be that
  let X = Y in A end
means "A, evaluated in a local scope where X refers to Y". Reasoning:
often (e.g. in JavaScript), 'let' sets something in a local scope, and I
think Haskell has a construct like this? It's been a while since I
played around with Haskell though... In an as-direct-as-possible Python
translation, (lambda X=Y: A)()


isqrt = (lambda n: 0 if n == 0 else
            (lambda r=isqrt(n//4):
                2*r if n < (2*r+1)**2 else 2*r+1)())

This is obviously the same as your multi-expression function, with the
addition of the integer division as suggested by Marko.


> The best I've come up with is this:
> 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
> but I don't understand the let ... in part so I'm not sure if I'm doing 
> it right.