range foreach lambda

bearophile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 17 06:10:37 PDT 2014


ddos:

> how do i add the elements in a and b elementwise

Several ways to do it:

void main() {
     import std.range, std.algorithm, std.array;

     immutable a = [1, 2, 3, 4];
     immutable b = [2, 3, 4, 5];

     int[] c1;
     c1.reserve(a.length); // Optional.
     foreach (immutable x, immutable y; a.zip(b))
         c1 ~= x + y;
     assert(c1 == [3, 5, 7, 9]);

     auto c2a = a.zip(b).map!(ab => ab[0] + ab[1]); // Lazy.
     assert(c2a.equal([3, 5, 7, 9]));
     const c2b = c2a.array;
     assert(c2b == [3, 5, 7, 9]);

     auto c3 = new int[a.length];
     c3[] = a[] + b[];
     assert(c3 == [3, 5, 7, 9]);

     int[4] c4 = a[] + b[];
     assert(c4 == [3, 5, 7, 9]);
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list