[Issue 18336] Add std.algorithm.findMatchingParen

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Jan 30 16:29:31 UTC 2018


https://issues.dlang.org/show_bug.cgi?id=18336

hsteoh at quickfur.ath.cx changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |hsteoh at quickfur.ath.cx

--- Comment #3 from hsteoh at quickfur.ath.cx ---
As Andrei suggested, one way to implement this would be something like this:

-----
R untilMatchingParens(R)(R range, dchar rightParen=')')
if (isInputRange!R)
{
    if (range.empty) return range; // base case
    auto leftParen = range.front; // <-- this is how we know what the starting
parens is
    range.popFront;

    int nesting = 1;
    foreach (ch; range)
    {
        if (ch == leftParen) nesting++;
        else if (ch == rightParen) nesting--;
        if (nesting == 0) break;
    }
    return range;
}
-----

Basically, the start of the range determines what the opening parens is, and
the optional argument specifies what the closing parens is.

Of course, the above implementation could be improved (e.g., using memchr or
whatever to find the parens characters), but this is just a proof-of-concept.

--


More information about the Digitalmars-d-bugs mailing list