Isn't using find with retro awkward?

Steven Schveighoffer schveiguy at yahoo.com
Wed Feb 16 10:10:41 PST 2011


On Wed, 16 Feb 2011 12:37:04 -0500, Andrej Mitrovic  
<andrej.mitrovich at gmail.com> wrote:

> 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]);
> }

Your code has a rather large design flaw.  It does not return a subrange  
to the original, it returns a new range.  That's not in the charter of  
find, find must return a portion of the original.  Not to mention it  
assumes R can be appended to.

For example, if I want to find the last 5 and change it to 6, I could do:

find(retro(r)).front = 6;

In your code, findBack(r).front = 6 does nothing.

-Steve


More information about the Digitalmars-d-learn mailing list