[Issue 18336] Add std.algorithm.findMatchingParen

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


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

Andrei Alexandrescu <andrei at erdani.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |andrei at erdani.com

--- Comment #4 from Andrei Alexandrescu <andrei at erdani.com> ---
(In reply to hsteoh from comment #3)
> 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.

Yes, with the amendment there is no default for the closing paren. Instead,
there's an overload without the closing paren:

R findMatchingParen(R)(R range) { ... }

That looks at range.front and then infers the closing paren as follows: ")" for
"(", "}" for "{", "[" for "]", ">" for "<", and perhaps a few Unicode fancy
parens too.

--


More information about the Digitalmars-d-bugs mailing list