On 09/17/2012 03:00 PM, Andrej Mitrovic wrote:
I need to iterate through two arrays and do some special comparisons,
but the arrays are not guaranteed to have the same length. lockstep
doesn't work with the "longest" policy, e.g.:

int[] a = [1, 2];
int[] b = [1, 2, 3];

foreach (aa, bb; lockstep(a, b, StoppingPolicy.longest))  // throws
{
}

What I would like to have is the ability to set a sentinel value when
.empty returns true for one of the arrays, this would enable this
policy to work. For example I could have:

foreach (aa, bb; lockstep(a, b, StoppingPolicy.longest, -1))  // sentinel is -1
{
     // if aa or bb doesn't exist it's set to -1
}

or alternatively aa/bb could be pointers, and the sentinel would
conveniently be null. Is anything like this in Phobos already?

I think you actually want .shortest, no? lockstep's cousin zip() and until() may help:

import std.stdio;
import std.range;
import std.algorithm;

void main()
{
    int i, j, k, l, m;
    int*[] a = [&i, null, &j];
    int*[] b = [&k, &l, &m];

    foreach (aa, bb;
             zip(StoppingPolicy.shortest, until!(x => x is null)(a), b))
    {
        writefln("%s and %s", aa, bb);
    }
}

Ali

Reply via email to