foreach ref very broken: fails to call front(val)

bearophile bearophileHUGS at lycos.com
Mon Jul 2 07:05:05 PDT 2012


On Monday, 2 July 2012 at 12:44:59 UTC, monarch_dodra wrote:
> I think this is a pretty serious bug: when one writes: 
> "foreach(ref a, range)", the underlying (ref'd) object will 
> ONLY get modified if the range object provides a "ref T 
> front()" method.

Somethig related, zip(a,b) allows to sort the two arrys, but you 
can't modify the arry items with a ref foreach:


import std.stdio: writeln;
import std.algorithm: sort;
import std.range: zip;

void foo1() {
     auto a = [10, 20, 30];
     auto b = [100, 200, 300];

     foreach (ref x, y; zip(a, b))
         x++;
     writeln(a);
}

void foo2() {
     int[] a = [1, 2, 3];
     string[] b = ["c", "b", "a"];
     writeln(zip(a, b)[2]);
     writeln(a, "\n", b);
     sort!("a[0] > b[0]")(zip(a, b));
     writeln(a, "\n", b);
}

void main() {
     foo1();
     foo2();
}


Output:

[10, 20, 30]
Tuple!(int,string)(3, "a")
[1, 2, 3]
["c", "b", "a"]
[3, 2, 1]
["a", "b", "c"]

Bye,
bearophile


More information about the Digitalmars-d mailing list