osdir.com

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]# Any SML coders able to translate this to Python?

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

On Tue, 4 Sep 2018 at 13:31, Steven D'Aprano <steve+comp.lang.python at pearwood.info> 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. > > > 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. I've not used SML much, but what you have looks right. let ... in is basically a local binding "let x = 12 in x+2" is saying "the value of x+2 with x set to 12". As I'm sure you realise (but I'll add it here for the sake of any newcomers who read this), the recursive approach is not natural (or efficient) in Python, whereas it's the natural approach in functional languages like SML. In Python an iterative solution would be better. Paul

- Prev by Date:
**Any SML coders able to translate this to Python?** - Next by Date:
**Any SML coders able to translate this to Python?** - Previous by thread:
**Any SML coders able to translate this to Python?** - Next by thread:
**Any SML coders able to translate this to Python?** - Index(es):