digitalmars.D.learn - Lambda Tuple with Map Reduce
- Salih Dincer (45/45) Apr 20 2022 ```d
- Salih Dincer (11/13) Apr 20 2022 It's my fault, here is the solution:
- Stanislav Blinov (3/17) Apr 20 2022 With the original version, I'm getting expected results with
- JG (2/6) Apr 20 2022 I think technically you should have save after range in that loop.
```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 79
Apr 20 2022
On Wednesday, 20 April 2022 at 08:04:42 UTC, Salih Dincer wrote:I get an unexpected result inside the second foreach() loop. Anyone know your reason?It's my fault, here is the solution: ```d foreach(fun; funs) { range.map!(a => fun(a)) .reduce!sum .write(" "); // Ok! } writeln; // "1115 188 102 86 47" ```
Apr 20 2022
On Wednesday, 20 April 2022 at 08:37:09 UTC, Salih Dincer wrote:On Wednesday, 20 April 2022 at 08:04:42 UTC, Salih Dincer wrote:With the original version, I'm getting expected results with 2.098.1. run.dlang.io with 'dmd' also shows expected results.I get an unexpected result inside the second foreach() loop. Anyone know your reason?It's my fault, here is the solution: ```d foreach(fun; funs) { range.map!(a => fun(a)) .reduce!sum .write(" "); // Ok! } writeln; // "1115 188 102 86 47" ```
Apr 20 2022
On Wednesday, 20 April 2022 at 08:04:42 UTC, Salih Dincer wrote:```d alias type = real; alias func = type function(type a); [...]I think technically you should have save after range in that loop.
Apr 20 2022