4 ms·
> Quite to the point, lambdas (anonymous closures) in Python are gimped. They are single-expression functions, which means no statements, even global/nonlocal q
by grondilu 10y ago
> Quite to the point, lambdas (anonymous closures) in Python are gimped. They are single-expression functions, which means no statements, even global/nonlocal qualifiers.
I remember once on rosettacode I wanted to write a Runge-Kutta function in Python with a lambda. I was stopped by the lack of variable assignment, until I remembered that they can be emulated by nesting function calls:
def RK4(f):
return lambda t, y, dt: (
lambda dy1: (
lambda dy2: (
lambda dy3: (
lambda dy4: (dy1 + 2*dy2 + 2*dy3 + dy4)/6
)( dt * f( t + dt , y + dy3 ) )
)( dt * f( t + dt/2, y + dy2/2 ) )
)( dt * f( t + dt/2, y + dy1/2 ) )
)( dt * f( t , y ) )
https://rosettacode.org/wiki/Runge-Kutta_method#using_lambda https://rosettacode.org/wiki/Runge-Kutta_method#using_lambda
- darkf 10y ago... Yeah, that's gnarly. :D That is emulating `let` using lambdas, though, and not mutable assignment. Still useful if you really want to nest them, but still immutable.
- grondilu 10y agoI don't know, isn't it possible to do the equivalent of mutable assignment if I use the same variable name several times? For instance for the equivalent of x = 3; x = x + 1; print(x): (lambda x: (lambda x: print(x))(x+1))(3);