Lambda Tuple with Map Reduce

Salih Dincer salihdb at hotmail.com
Wed Apr 20 08:04:42 UTC 2022


```d
alias type = real;
alias func = type function(type a);

void main()
{
   import std.range;
   auto range = 10.iota!type(14, .5);

   alias fun1 = (type a) => a * a;
   alias fun2 = (type a) => a * 2;
   alias fun3 = (type a) => a + 1;
   alias fun4 = (type a) => a - 1;
   alias fun5 = (type a) => a / 2;

   import std.typecons;
   auto funs = tuple(fun1, fun2, fun3, fun4, fun5);

   import std.stdio;
   foreach(fun; funs)
   {
	fun(10).write(" "); // Perfect...
   }
   writeln; // 100 20 11 9 5

   import std.algorithm;
   auto sum = (type a, type b) => a + b;
   foreach(fun; funs)
   {
	range.map!fun
	     .reduce!sum
	     .write(" "); // Opps!
   }
   writeln; // 1115 1115 1115 1115 1115

   range.map!fun1.reduce!sum.write(" "); // "1115" Ok!
   range.map!fun2.reduce!sum.write(" "); // "188"  Ok!
   range.map!fun3.reduce!sum.write(" "); // "102"  Ok!
   range.map!fun4.reduce!sum.write(" "); // "86"   Ok!
   range.map!fun5.reduce!sum.write(" "); // "47"   Ok!
} /*
    * EXPECTED RESULTS:
    *
    *  1115 188 102 86 47
    *
    */
```
Hi all,

I get an unexpected result inside the second foreach() loop. 
Anyone know your reason?

SDB at 79


More information about the Digitalmars-d-learn mailing list