Better Return Value for findSplit*()

Jakob Ovrum via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 16 02:56:20 PDT 2015


On Saturday, 16 May 2015 at 09:36:30 UTC, Per Nordlöw wrote:
> After having written a lot of text pattern matching functions 
> using Phobos' findSplit, findSplitBefore, findSplitAfter, and 
> some more I've written myself I've come to the conclusion that 
> I would like to enhance these functions to instead return a 
> struct instead of tuples. This struct would typically look like
>
> struct FindSplit(T)
> {
>     T[3] data;
>     T first() { return data[0]; }
>     T separator() { return data[1]; }
>     T second() { return data[2]; }
>     T opIndex(size_t i) return { return data[i]; }
>     cast(T : bool)() { return !separator.empty; }
> }
>
> This would enable the following useful syntax:
>
>     if (const split = line.findSplit(`-`))
>     {
>         // do something with split
>     }
>
> instead of current
>
>     const split = line.findSplit(`-`)
>     if (!split[1].empty)
>     {
>     }
>
> which is a constantly reoccurring pattern in D code processing 
> text.
>
> The cons I can think of is that split[N] (N being a 
> CT-constant) will occurr in run-time instead of compile-time 
> and of course that people relying on that return-type of 
> findSplit() being a tuple will cause code-breakage.
>
> What do you guys think;
>
> - Add extra template-param that returns struct instead and make 
> the current behaviour deprecated?
> - Will happen for D3? :)
> - Will never happen?
>
> Destroy!

It can be implemented in a backwards-compatible way as a subtype 
of a Tuple.

struct FindSplit(R)
{
     Tuple!(R, "pre", R, "separator", R, "post") asTuple;

     bool opCast(T : bool)()
     {
         return !asTuple.separator.empty;
     }

     alias asTuple this;
}

Tuple!(R, "pre", R, "separator", R, "post") is a subtype of 
Tuple!(R, R, R), which should be the current return type.


More information about the Digitalmars-d-learn mailing list