3 ms·
I don't know python, so I don't know if anonymous functions have been crippled there, but in other languages anonymous functions are used to do things such as c
by burgerbrain 15y ago
I don't know python, so I don't know if anonymous functions have been crippled there, but in other languages anonymous functions are used to do things such as create closures (not stateless).
For example, in scheme:
> (define (foo x) (lambda (y) (+ x y)))
> (define bar (foo 10))
> (bar 5)
15
This sort of thing is of course immensely useful.
- andrewaylett 15y agoYou can do the same in Python, with named functions or lambdas: >>> def foo(x): ... def add(y): ... return x + y ... return add ... >>> bar = foo(10) >>> bar(5) 15
- masklinn 15y agoAnd it takes twice the token count and lowered readability for no gain whatsoever.
- burgerbrain 15y agoNo gain at all? How do you figure?
- olavk 15y agoTwice the token count? How did you get that?
- cyrus_ 15y agofoo = lambda x: lambda y: x + y bar = foo(10) This is perfectly correct Python code too if you prefer. The only real thing with Python's lambdas is that, because Python makes a distinction between statements and expressions, you can't easily do things like use temporary variables inside a lambda, but cases like that are rare and are typically more readable with a separate standalone function definition anyway.