D idom for removing array elements

albert-j via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 29 13:41:57 PST 2017


On Saturday, 28 January 2017 at 11:54:58 UTC, cym13 wrote:
> 

I am trying to wrap my head around lazy evaluation during 
filtering/mapping, but there's something I don't understand.
I want to create an array, square some elements, remove some 
elements from original array and add the squared ones to the 
original array:

     import std.stdio, std.algorithm, std.array;

     int[] arr;
     foreach (i; 0..10)
         arr ~= i;

     writeln("Original array: ",arr);
     // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -- OK

     auto arrMap = arr.filter!(x => x > 5).map!(x => x^^2);
     writeln("arrMap: ", arrMap);
     // [36, 49, 64, 81] -- OK

     int[] toRemove = [1, 2, 9];
     arr = arr.remove!(x => toRemove.canFind(x)).array;

     writeln("Original array after removal: ", arr);
     // [0, 3, 4, 5, 6, 7, 8] -- OK

     arr ~= arrMap.array;

     writeln("Original array after removal and concatenation: ", 
arr);
     // [0, 3, 4, 5, 6, 7, 8, 64, 49, 64, 81] -- what?

The last result is not what I wanted. I would expect [0, 3, 4, 5, 
6, 7, 8] and [36, 49, 64, 81] concatenated into [0, 3, 4, 5, 6, 
7, 8, 36, 49, 64, 81], but something else is happening here.
It looks like arr = arr.remove!....  is messing things up, but 
why?



More information about the Digitalmars-d-learn mailing list