foreach thoughts

Manu turkeyman at gmail.com
Tue Jan 14 00:22:44 PST 2014


So, the last few days, 2 things have been coming up constantly.

foreach is like, the best thing about D. But I often get caught by 2 little
details that result in my having to create a bunch more visual noise.

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;
  ...
}

I often feel like I want something like this where I would have the
opportunity to add that additional term I lose with a traditional for loop:
  foreach(i, t; things; t.someCondition)


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;
  ...
}


I'm finding in practise that at least one of these seems to pop up on the
vast majority of loops I'm writing. It produces a lot of visual noise, and
I'm finding it's quite a distraction from the otherwise relative tidiness
of my code.

How have others dealt with this? I wonder if it's worth exploring a 3rd
term in the foreach statement?

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).
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.
It's also really hard to debug std.algorithm statements, you can't step the
debugger anymore.

Also, I have to import std.algorithm, which then imports the universe... >_<
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20140114/08f9afa2/attachment-0001.html>


More information about the Digitalmars-d mailing list