4 ms·
If P is a built-in function taking a single argument, or one that's already been defined, no. That's often not the case, though, and using a simple lambda is an
by etal 18y ago
If P is a built-in function taking a single argument, or one that's already been defined, no. That's often not the case, though, and using a simple lambda is annoying and usually less efficient the rest of the time.
For example,
filter(isfile, os.listdir(some_dir))
is cleaner than:
(f for f in os.listdir(some_dir) if isfile(f))
But
filter(lambda f: f.endswith('.py'), os.listdir(some_dir))
is worse than:
(f for f in os.listdir(some_dir) if f.endswith('.py'))
Ruby's blocks are something to be jealous of, in this case. List comprehensions and generator expressions have other merits, though.
- shiro 18y agoI think this is the case that the choice of the syntax (and a bit of semantics) did affect the choice of API. I'm not a Python programmer, but I can see in your second example that they would prefer comprehensions to filter. If there were curring or some convenient partial application syntax in the language, using 'filter' can be more natural choice. In Gauche Scheme, pa$ is a built-in partial applicaiton and I'd write: (filter (pa$ string-suffix? ".py") (sys-readdir some-dir)) Or in Haskell: getDirectoryContents somedir >>= return . filter (isSuffixOf ".py") In general I'd rather write this in Gauche, for a regexp object is applicable: (filter #/\.py$/ (sys-readdir some-dir)) So, if you have more variations than the bare lambda to create a higher order function (either in currying, partial application, or promoting objects to applicable something, etc), the more the functions such as filter, fold etc become useful. If you need to fall back to lambda for most of times, it would be natural that using those fns becomes annoying.
- pg 18y agoArc's [] notation would help in the second case. filter([_.endswith('.py')], os.listdir(some_dir)) I've found that one of the most important things to eliminate from a program is unnecessary names. Introducing a variable is more than 1 token's worth of conceptual load.
- eru 18y agoI wish there was an easy syntax (in Python) for not only map and filter - but for something like reduce/foldr/foldl as well. You still have to write loops to do this (or use reduce.)
- etal 18y agoMe too. I think the introduction of the functional module will actually be good, because there's less resistance to adding clever features for higher-order functions in the standard library than there is in the core language (in Python, at least, since it aims to be small and beginner-friendly). Look at the itertools module to see how that turned out -- lots of useful tricks borrowed from the ML family, and you can "buy it by the yard".