The rfind challenge

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Jan 15 12:59:17 PST 2013


On 1/15/13 2:07 PM, Phil Lavoie wrote:
> Continuing with reversible ranges:

I don't think .reverse will take us far enough. Won't work with arrays 
which kinda puts a monkey wrench into everything. r1.before(r2) works 
much better:

R rfind(R, E)(R r, E e) {
   auto original = r.save;
   for (; !r.empty; r.popBack) {
     if (r.endsWith(e)) break;
   }
   return original.before(r);
}

The generic implementation of before is trivial:

auto before(R)(R theBuck, R stopsHere) {
   static struct Result {
     bool empty() { return r1 is r2; }
     auto ref front() { return r1.front; }
     void popFront() { r1.popFront; }
     private R r1, r2;
   }
   return Result(theBuck, stopsHere);
}

For random-access ranges:

auto before(R)(R theBuck, R stopsHere) {
   return theBuck[0 .. theBuck.length - stopsHere.length];
}

(Glossing over checks and balances etc.)

Bidirectional ranges would need to implement before natively to return 
the same type as the original range.

The question is whether before() is enough for many other algorithms 
we'd want to define.


Andrei


More information about the Digitalmars-d mailing list