by aaronchall · 9y ago · 0 comments
You mean these critics find
>>> map(lambda x: x**2, filter(lambda x: not x % 2, range(11)))
preferable to the "fragmented": def square(x):
return x ** 2
def is_even(x):
return not x % 2
>>> (square(x) for x in range(11) if is_even(x))
Both result in the same lazy iteration (to see results below - requires materialization with a constructor like list or tuple), but I find the "fragmented" approach much more readable (so long as the functions do what their name says they do - I have seen Python where they actually did the opposite...) >>> list((square(x) for x in range(11) if is_even(x)))
[0, 4, 16, 36, 64, 100]
>>> list(map(lambda x: x**2, filter(lambda x: not x % 2, range(11))))
[0, 4, 16, 36, 64, 100] # square even numbers
range(11)
.filter(lambda x: not x % 2)
.map(lambda x: x ** 2)
However such a chaining API is not practical in python, because lambda syntax is voluntarily crippled to one expression only.For example I often end up doing:
something(
"Template string {thing}"
.format(thing=33)
) label = "Template string {thing}".format(thing=33)
something(label)In the real world you filter water to get the water. In most programming languages filter() is more like a strainer or colander.
My guess is you ran into someone stubbornly insisting on the meaning of the word filter despite all evidence.