Idiomatic way of writing nested loops?

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 17 20:36:04 PDT 2017


On Monday, 17 July 2017 at 11:07:35 UTC, Anton Fediushin wrote:
> Hello! What is the best way of rewriting this code in idiomatic 
> D manner?
> ------
> foreach(a; ["foo", "bar"]) {
>   foreach(b; ["baz", "foz", "bof"]) {
>     foreach(c; ["FOO", "BAR"]) {
>       // Some operations on a, b and c
>     }
>   }
> }
> ------
>
> Every array has at least 1 element, and adding/removing new 
> "nested loops" should be as easy as possible.
>
> Also, I have a question about running this in parallel: if I 
> want to use nested loops with `parallel` from 
> `std.parallelism`, should I add `parallel` to every loop like 
> this?
> ------
> foreach(a; ["foo", "bar"].parallel) {
>   foreach(b; ["baz", "foz", "bof"].parallel) {
>     foreach(c; ["FOO", "BAR"].parallel) {
>       // Some operations on a, b and c
>     }
>   }
> }
> ------
> I am worried about running thousands of threads, because in 
> this case first `parallel` runs 2 tasks, every task runs 3 
> tasks and every task runned inside a task runs 2 more tasks.
>
> So, how to write this in idiomatic D manner and run it _if 
> possible_ in parallel?

With regards to parallel, only use it on the outermost loop. 
Assuming you have more items in the outermost loop than you do 
threads parallelising more than one loop won't net you any speed.


More information about the Digitalmars-d-learn mailing list