digitalmars.D.learn - Parallel foreach iteration with Associative Arrays
- Kirill (10/10) Apr 16 2021 I'd like to iterate over an associative array and output it's key
- Paul Backus (15/25) Apr 16 2021 `parallel` requires a range [1], and an associative array is not
- Kirill (2/16) Apr 16 2021 That worked! Thanks you!
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.
Apr 16 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
Apr 16 2021
On Saturday, 17 April 2021 at 02:14:50 UTC, Paul Backus wrote:
`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
That worked! Thanks you!
Apr 16 2021








Kirill <kirill.saidov mail.com>