Iterating over multiple collections in parallel
Jarrett Billingsley
kb3ctd2 at yahoo.com
Thu Jul 3 09:37:39 PDT 2008
"Koroskin Denis" <2korden at gmail.com> wrote in message
news:op.udp4pcjxenyajd at proton.creatstudio.intranet...
> If found myself solving the same problem again and again:
> how to implement simultaneous iteration over two (or more collections)?
>
> suppose, we have the arrays:
> int[] a = [1, 2, 3];
> int[] b = [1, 4, 9];
>
> and would like to multiply them per-component, like this:
>
> int[] c = new int[a.length];
> for (int i = 0; i < a.length; ++j) {
> c[i] = a[i] * b[i];
> }
>
> Since foreach is the prefered (and sometimes the only) way to iterate over
> collection, there should be a way to iterate over multiple collections
> simultaneously, like (just an example) this:
>
> int[] c = new int[a.length];
> foreach (i : a; j : b; ref k : c) {
> k = a + b;
> }
>
> But this isn't supported (yet?)
> More complicated example would be an iterating over two (or more)
> collection with *no* random access iterators available, opApply only.
>
> I spend a lot of time on this and have found no solution how to do it with
> existing D feature set, but this is surely doable with a few
> inter-function gotos and an exception if collections sizes don't match.
> It's just a small layer written in asm, nothing more.
>
> How about an enhancement proposal? :)
It's something Walter mentioned before, but without any kind of public
"plan" of these ideas he has, there's no way to know if it's even on his
plate.
I think the syntax he used was something like this:
foreach(a, b; c)(d, e; f) { blah }
In any case, it's difficult in the general case to do parallel iteration
with D's inside-out iterators. To do it generally, you'd have to use
coroutines. But you can currently write a templated zip to iterate over
arrays simultaneously, only because they're so easy to iterate over. I'm
sure downs will post something horrid-looking that you can look over.
More information about the Digitalmars-d
mailing list