Better Return Value for findSplit*()

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 16 02:36:29 PDT 2015


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!


More information about the Digitalmars-d-learn mailing list