Parallel foreach iteration with Associative Arrays

Paul Backus snarwin at gmail.com
Sat Apr 17 02:14:50 UTC 2021


On Saturday, 17 April 2021 at 01:57:34 UTC, Kirill wrote:
> I'd like to iterate over an associative array and output it's 
> key and value using parallel from std.parallelism.
>
> But I get an error message: ParallelForeach!(int[string]) error 
> instantiating.
>
> My code:
>
> auto example = ["apples": 100, "orange": 250, "banana": 175];
> foreach(key, value; parallel(example)) { writeln(key, ": ", 
> value); }
>
> What am I doing wrong?
>
> Thanks in advance.

`parallel` requires a range [1], and an associative array is not 
a range. To get a range of an AA's keys and values, you can use 
the method `.byKeyValue`:

     foreach (pair; parallel(example.byKeyValue)) {
         writeln(pair.key, ": ", pair.value);
     }

If you're confused about what a "range" is, the short answer is 
that it's kind of like an iterator. For the long answer, check 
out Andrei Alexandrescu's article "On Iteration" [2], or the 
"Ranges" chapter of Ali Çehreli's "Programming in D" [3].

[1] 
https://phobos.dpldocs.info/std.parallelism.TaskPool.parallel.2.html
[2] https://www.informit.com/articles/printerfriendly/1407357
[3] http://ddili.org/ders/d.en/ranges.html


More information about the Digitalmars-d-learn mailing list