More Generic Variants of findSplit.*() in Demangling/Parsing

"Nordlöw" via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 14 14:04:03 PDT 2014


On Thursday, 14 August 2014 at 20:48:42 UTC, Nordlöw wrote:
> Ooops, I just realized that we can't express current Phobos 
> implementations using my variant. Current algorithms take 
> ranges not range values as a needle. My mistake. Are my 
> overloads still wanted?

Ok. I finally understood that a simplification was the way to go:

/** Simpler Variant of Phobos' findSplitBefore. */
auto findSplitBefore(alias pred, R1)(R1 haystack) if 
(isForwardRange!R1)
{
     static if (isSomeString!R1 ||
                sRandomAccessRange!R1)
     {
         auto balance = haystack.find!pred;
         immutable pos = haystack.length - balance.length;
         return tuple(haystack[0 .. pos],
                      haystack[pos .. haystack.length]);
     }
     else
     {
         auto original = haystack.save;
         auto h = haystack.save;
         size_t pos;
         while (!h.empty)
         {
             if (unaryFun!pred(h.front))
             {
                 h.popFront();
             }
             else
             {
                 haystack.popFront();
                 h = haystack.save;
                 ++pos;
             }
         }
         return tuple(takeExactly(original, pos),
                      haystack);
     }
}

unittest
{
     import std.algorithm: equal;
     import std.ascii: isDigit;
     auto x = "11ab".findSplitBefore!(a => !a.isDigit);
     assert(equal(x[0], "11"));
     assert(equal(x[1], "ab"));
}

Should this go into Phobos?


More information about the Digitalmars-d-learn mailing list