range foreach lambda

bearophile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 17 05:27:33 PDT 2014


ddos:

> auto twice  = function (int x) => x * 2;

"function" is not necessary. And generally it's better to assign 
to immutables, unless you need to mutate the variable "twice" 
later.


> how can i apply the function to each element in a without using 
> a forloop? - is there a function to do this?

Generally such range based functions are designed for a 
functional style of coding, so a map is meant to produce a new 
(lazy) range.

If you really want to mutate in-place, you can use a copy:


void main() {
     import std.algorithm;
     auto a = [1, 2, 3, 4, 5];

     immutable twice = (int x) => x * 2;

     a.map!(x => x * 2).copy(a);
     assert(a == [2, 4, 6, 8, 10]);
}


But this could introduce bugs, so better to limit the number of 
times you use similar code.

So this is more idiomatic and safer:

void main() {
     import std.algorithm;

     immutable data = [1, 2, 3, 4, 5];
     auto result = data.map!(x => x * 2);
     assert(result.equal([2, 4, 6, 8, 10]));
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list