Defining a static array with values in a range

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jan 22 10:22:59 PST 2015


On Thursday, 22 January 2015 at 17:45:59 UTC, tcak wrote:
> So, at the end of the day (I left working on my Matcher class 
> in the morning waiting an answer for this question), there is 
> nothing to convert ['a'..'d', '0'..'3'] to ['a', 'b', 'c', 'd', 
> '0', '1', '2', '3'] at compile time automatically.

There is rarely never a way to do something in D, if you want to 
hack around a bit.

import std.stdio;

@property charRange(string spec)()
{
     import std.algorithm;
     import std.ascii;
     import std.conv;
     import std.range;
     import std.string;

     return spec.split(',').map!((s)
     {
         s = s.strip;
         auto start = s[1..$].front;
         auto end = s[0..$-1].back;

         return iota(start, end + 1).map!(c => cast(char)c).array;
     }).array.join;

}


void main(string[] argv)
{
     auto t = charRange!q{ 'a'..'z', 'A'..'Z', '0'..'9' };

     
//abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
     writeln(t);
}

This is very rough code, as it only works for ASCII codepoints, 
and it can't do backward intervals, but you get the idea.


More information about the Digitalmars-d-learn mailing list