Splitting Ranges using Lambda Predicates

Artur Skawina via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 11 04:42:24 PDT 2014


On 06/11/14 00:31, "Nordlöw" via Digitalmars-d-learn wrote:
>> Either way, it shouldn't be too hard to implement. Base it off "splitter!pred", which is actually quite trivial. AFAIK, your
> 
> What do you mean by basing it off splitter!pred - should I start with some existing splitter algorithm in Phobos or start from scratch?

Starting from scratch is actually not a bad idea, at least for this kind
of trivial functionality. A working version can be written in less time
than copying, analyzing and modifying another implementation...

For example (using monarch_dodra's test inputs):

   auto slicer(alias PRED, R)(R r) {
      import std.algorithm, std.array, std.range;
      struct Slicer {
         R r;
         size_t c;
         bool empty() @property const { return r.empty; }
         auto front() @property {
            c = r.dropExactly(1).countUntil!PRED()+1;
            if (c==0)
               c = r.length;
            return r.takeExactly(c);
         }
         void popFront() { r.popFrontN(c); }
      }
      return Slicer(r);
   }

   auto slicer(R)(R r) {
      import std.uni;
      return slicer!(a=>isUpper(a))(r);
   }

   void main() {
      import std.stdio, std.range;
      "SomeGreatVariableName"  .slicer().writeln();
      "someGGGreatVariableName".slicer().join(" ").writeln();
      "".slicer().writeln();
      "a".slicer().writeln();
      "A".slicer().writeln();
   }

artur


More information about the Digitalmars-d-learn mailing list