3 ms·
It's pretty common to define "higher-order" functions in functional programming. These will sometimes be applied to code blocks. For example, Python's with st
by raphaelj 3y ago
It'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.