foreach thoughts

deadalnix deadalnix at gmail.com
Tue Jan 14 00:29:27 PST 2014


On Tuesday, 14 January 2014 at 08:23:05 UTC, Manu wrote:
> 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)
>

until

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

filter

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

We have the tool to build ranges that does what you ask for and 
feed foreach with them.


More information about the Digitalmars-d mailing list