std.algorithm.map with side-effects

Joseph Rushton Wakeling via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 5 15:38:41 PST 2014


Here's a little experiment I was trying out earlier today in order to try and 
convert foreach-style code to using UFCS of ranges:

//////////////////////////////////////////////
import std.algorithm, std.range, std.stdio;

void main()
{
     size_t s = 0;

     void essify(size_t n)
     {
         writeln("n = ", n);
         ++s;
     }

     auto filteredRange = iota(0, 10).filter!(a => (a % 2));

     filteredRange.map!(a => essify(a));

     writeln(s);

     foreach (n; filteredRange)
     {
         essify(n);
     }

     writeln(s);
}
//////////////////////////////////////////////

I'd assumed the two uses of filteredRange would produce equivalent results, but 
in fact the transformation using map does nothing -- the writeln statement 
inside the essify() function never gets triggered, suggesting the function body 
is never executed.

Can anyone advise why, and whether there's a nice range iteration option to 
ensure that this function gets called using each element of the filteredRange?


More information about the Digitalmars-d-learn mailing list