Defining a static array with values in a range
bearophile via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jan 22 02:13:33 PST 2015
tcak:
> Well, that's just disguising what we can't do.
When the a..b syntax was added to foreach() someone criticized
that syntax saing it's a "one trick pony", and indeed I don't
know why Walter didn't make it a little more first-class.
But note that in D the a..b ranges are always open on the right,
so 'a'..'z' can't include the 'z'.
What do you think of this?
import std.stdio, std.range, std.algorithm, std.array;
auto charInterval(in char a, in char b) pure nothrow @safe @nogc {
return iota(a, b + 1).map!(i => cast(char)i);
}
void main() @safe {
char[] arr = chain(charInterval('a', 'z'),
charInterval('A', 'Z'),
charInterval('0', '9')).array;
arr.writeln;
}
charInterval can of course become eager too, so you just need ~
to concatenate the results:
import std.stdio, std.range, std.algorithm, std.array;
char[] charInterval(in char a, in char b) pure nothrow @safe {
return iota(a, b + 1).map!(i => cast(char)i).array;
}
void main() @safe {
char[] arr = charInterval('a', 'z') ~
charInterval('A', 'Z') ~
charInterval('0', '9');
arr.writeln;
}
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list