For example, I find this much clearer as a one-liner (Python):
validated_items = filter(is_validated, items)
rather than validated_items = []
for item in items:
if is_validated(item):
validated_items.append(item)validated_items = [x for x in items if is_validated(x)]
validated_items = [_ for _ in items if is_validated(x)]
where _ is used as a safe variable that can always be clobbered. (Though this does also clash with its use as a gettext function for strings).
validated_items = items.select { |item| is_validated?(item) }
Though I'd expect a check for validation to be an instance method, so it'd probably look like: validated_items = items.select(&:validated?)Ruby seems to be going down the same path as Perl in trying to make all possible combinations of characters valid programs.
my @validated = grep { is_validated($_) } @items;
I'd argue the Perl version is clearer... assuming you know its syntax, that is. validated_items = items.select(&method(:is_validated?))
(Typed on my phone but I'm pretty sure that's the right syntax)Does it return elements matching the predicate or not matching it? I struggled with this for a while in CS.
After learning different programming languages and getting some field experience I noticed that the `filter` pattern is pretty common in the programming world. It's one of those pervasive functional patterns that are so practical that they were included at some point in imperative languages.
It, I dunno, FILTERS a collection keeping only certain elements (those that match the filter)? What else would it possibly do? Besides a standard CS term, it's also a concept from real life...
To me the name is crystal clear.
Ponder for a second the phrases, "filtered water", "coffee filter", "camera filter", etc. In all of those cases, you are interested in the set without the filtered thing, not with.
Compare this to "select" which is a much clearer name.
Filtered is akin to "cleansed" (it refers to the "main body") not akin to "picked out" (which would have applied to the undesirable elements.
It's actually the water (or the light, in the case of camera filter) that's filtered (hence the name "filtered water" and not "filtered dust and detritus").
The other stuff is not what's being filtered -- just what's "filtered out".
Honestly, when I see people complaining that the code is "too clever", my default reaction is: programming is a profession, you're supposed to learn new stuff and get better, not complain that something is beyond what they taught you in Programming 101.