On Wednesday, 13 July 2016 at 09:59:30 UTC, celavek wrote:
Hi,

I am trying to use the function "mismatch" from std.algorithm.comparison like so:

int count = 0;
auto m = mismatch(lhs, rhs);

while (!m[0].empty)
{
    ++count;
    m = mismatch(m[0], m[1]);
}

That goes into an infinite loop. What does mismatch return when it cannot
actually find a mismatch? Is the return value immutable?
I do not get any warnings from the compiler(dmd).

The return value is described as:

"a tuple with the reduced ranges that start with the two mismatched values"

This means given the following:

void main()
{
    import std.algorithm : mismatch;
    import std.stdio : writeln;

    auto lhs = [10, 20, 1, 22, 33, 44];
    auto rhs = [10, 20, 2, 22, 33, 44];

    auto m = mismatch(lhs, rhs);
    writeln(m[0]);
    writeln(m[1]);
}

The ranges following are printed:

[1, 22, 33, 44]
[2, 22, 33, 44]

If you feed these back to mismatch, the 1 and the 2 are sill the mismatched values, so the return will again be identical:

[[1, 22, 33, 44],[2, 22, 33, 44]]

This is why you are getting an infinite loop, because the tuple values you get from the first call are fed back into mismatch infinitely. For your loop to work, you would need to pop the first value from each range in the tuple. Something like this:

```
void main()
{
    import std.algorithm : mismatch;
    import std.stdio : writeln;

    // This example is using arrays as ranges,
    // so this is needed to give them the
    // correct interface
    import std.array : popFront, empty;

    auto lhs = [10, 20, 1, 22, 33, 44];
    auto rhs = [10, 20, 2, 22, 33, 44];

    auto m = mismatch(lhs, rhs);
    while(!m[0].empty && !m[1].empty) {
        m[0].popFront();
        m[1].popFront();
        m = mismatch(m[0], m[1]);
    }
    writeln("empty");
}
```

The return value when there is no mismatch is a tuple of two empty ranges. I've never used mismatch, but I learned everything I needed about the return values beyond what the documentation tells me by printing the return to the screen. Whenever you are confused about what a range-based function returns, writeln is your friend and can certainly save you some time.


Reply via email to