Isn't using find with retro awkward?

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed Feb 16 09:37:04 PST 2011


Quick fix:

import std.stdio;
import std.range;
import std.array;

auto findBack(alias pred = "a == b", R, E)(R haystack, E needle)
    if (isBidirectionalRange!R)
{
    R result;

    size_t index;
    auto reversed = retro(haystack);
    bool found;

    foreach (item; reversed)
    {
        index++;
        if (item == needle)
        {
            found = true;
            break;
        }
    }

    if (found)
    {
        while (index)
        {
            result ~= reversed.front;
            reversed.popFront;
            index--;
        }
    }

    return retro(result);
}

void main()
{
    auto orig = [5, 1, 2, 3, 4, 5, 1];

    auto result = findBack(orig, 4);
    assert(array(result) == [4, 5, 1]);
}


More information about the Digitalmars-d-learn mailing list