iteration over a string

bearophile bearophileHUGS at lycos.com
Tue May 28 03:20:51 PDT 2013


Timothee Cour:

>> string a="ΩΩab";
>> auto b1=a.map!(a=>"<"d~a~">"d).array;
>> writeln(b1);//["<Ω>", "<Ω>", "<a>", "<b>", "", ""]
>> Why are there 2 empty strings at the end? (one per Omega if 
>> you vary the
> number of such symbols in the string).
>
> The above is just weird; is that a bug?

I think it's a bug, it's shown here, I will put it in Bugzilla:

import std.stdio: writeln;
import std.algorithm: map;
import std.array: array;
void main() {
     string a = "ΩΩab";
     a.map!(a => "<"d ~ a ~ ">"d).writeln;
     a.map!(a => "<"d ~ a ~ ">"d).array.writeln;
}


The output shows that maybe it's a problem of array():

["<Ω>", "<Ω>", "<a>", "<b>"]
["<Ω>", "<Ω>", "<a>", "<b>", "", ""]



> For input ranges ranges, I don't understand why the compiler 
> can't accept
> the foreach(i,ai;a) syntax:
>
> it should behave as follows:
> foreach(i , ai; a){expr}
>
> rewritten as:
> for(size_t i=0, ai=a.front; !a.empty; a.popFront;){expr}
>
> but it doesn't compile (it only accepts foreach(ai;a){expr}

The idea must work in all cases. For opApply, built-in arrays, 
built-in associative arrays and for ranges. I think it causes 
some clashing. If you will find it causes no clashing, then it's 
a candidate to become an enhancement request.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list