5 ms·
can you make anonymous functions with more than 1 expression now?
by amne 3y ago
can you make anonymous functions with more than 1 expression now?
- PurpleRamen 3y agoJust curious, but from a pragmatic view, what is the advantage of using anonymous functions instead of named functions for any mildly complex code?
- raphaelj 3y agoIt's pretty common to define "higher-order" functions in functional programming. These will sometimes be applied to code blocks. For example, Python's with statement could have been entirely programmed as a library function if lambas supported code blocks: with(open("file.txt"), lambda f: content = f.read() return sum(int(c) for c in content.split(" ")) ) Functional languages usually have a pretty limited "core" and implement most of their features through their standard library, usually using higher-order functions, overloaded operators ...
- PurpleRamen 3y agoBut I can do all that with python already? Your example would work this way too: def _(f): content = f.read() return sum(int(c) for c in content.split(" ")) with(open("file.txt"), _)
- sodapopcan 3y agoI don't think they were saying you can't do it in Python, just offering what is arguably a nicer syntax, but of course that is subjective. The anonymous function version lets you write things in the order they happen and also "binds" the operations together, ie, someone can't accidentally add a completely unrelated line between the `def` and the `with`. It ultimately doesn't matter, people just get used to the conventions of their preferred languages and we all trudge on.
- phailhaus 3y agoReadability and scoping are two big advantages. Anonymous functions are often short and sweet, but also highly specific to a single section of the code. It's not meant to be reused. Having to name that one-off use case and hoist it into a function elsewhere makes it harder to maintain and understand. With proper anonymous functions, you can just read through it in one go.
- PurpleRamen 3y agoBut you don't need to name it big or maintain it somewhere else? Just use a throwaway name and write it where you use it. I mean python even allows overriding functions with the same name in the same scope. You could literally go with using just the same name everywhere.
- biorach 3y agoTrue, but you're missing the point.
- PurpleRamen 3y agoThen what is the point?
- phailhaus 3y agoReadability. If you're using the same name everywhere, then your code is really hard to understand for other devs: val = my_list.reduce(foobar) What is even going on here?
- cmcconomy 3y agoone option is to define your function inline, directly above the line where you would have liked to write the complex anonymous function. I guess if you are worried about namespace pollution you can 'del' the symbol afterward.
- hsfzxjy 3y agoShameless plug. I've once made a library for this https://github.com/hsfzxjy/lambdex https://github.com/hsfzxjy/lambdex