foreach thoughts
Jakob Ovrum
jakobovrum at gmail.com
Tue Jan 14 00:36:52 PST 2014
On Tuesday, 14 January 2014 at 08:23:05 UTC, Manu wrote:
> 1. A termination condition (ie, while)
>
> foreach(t; things) iterates each thing, but it's common in
> traditional for
> loops to have an && in the second 'while' term, to add an
> additional
> termination condition.
> for(i=0; i<things.length && things[i].someCondition; ++i)
>
> Or with foreach:
> foreach(i, t; things)
> {
> if(t.someCondition)
> break;
> ...
> }
foreach(t; things.until!(t => t.someCondition))
{
}
Unfortunately foreach over a range does not automatically support
an index loop variable. We could add something like
std.range.enumerate to support this, but I think it's a common
enough requirement that a language amendment is warranted (there
are some subtleties involved in implementing it though -
specifically when combined with automatic tuple expansion).
> 2. A filter
>
> The other thing is the ability to skip uninteresting elements.
> This is
> typically performed with the first line of the loop testing a
> condition,
> and then continue:
> foreach(i, t; things)
> {
> if(!t.isInteresting)
> continue;
> ...
> }
foreach(t; things.filter!(t => t.isInteresting))
{
}
Ditto about the index loop variable.
> I've tried to approach the problem with std.algorithm, but I
> find the
> std.algorithm statement to be much more noisy and usually
> longer when the
> loops are sufficiently simple (as they usually are in my case,
> which is why
> the trivial conditions are so distracting by contrast).
The two examples above look a *lot* cleaner and less noisy
(declarative!) to me than the imperative approach using if-break
or if-continue.
> I also find that the exclamation mark overload in typical
> std.algorithm
> statements tends to visually obscure the trivial condition I'm
> wanting to
> insert in the first place.
You'll have to get used to the exclamation mark, otherwise you'll
never be able to fully appreciate D's generic programming. I
quite like it - I don't think there's anything objectively ugly
about it.
> Also, I have to import std.algorithm, which then imports the
> universe... >_<
This is fixable. We shouldn't reach for language changes to
compensate for library deficiencies.
More information about the Digitalmars-d
mailing list