Comment #0 by bearophile_hugs — 2015-01-23T14:31:46Z
I suggest to add a "std.algorithm.mean" or "std.algorithm.average" function that scans its input range only once, because it's commonly useful, and because naive user-level computations of the average of a lazy range scan it two times:
void main() {
import std.stdio, std.range, std.algorithm;
auto items = iota(100, 250);
immutable len = items.walkLength;
immutable mean1 = items.sum / double(len);
mean1.writeln;
}
To scan it only once you have to write code that is imperative-style, or not so easy if functional-style:
void main() {
import std.stdio, std.range, std.algorithm, std.typecons;
auto items = iota(100, 250);
immutable pair = reduce!((a, b) => tuple(a[0] + 1, a[1] + b))
(tuple(0u, 0.0), items);
writeln(pair[1] / double(pair[0]));
}
A possible usage example of std.algorithm.mean (it defaults to resulting a double):
void main() {
import std.stdio, std.range, std.algorithm;
auto items = iota(100, 250);
writeln(items.mean!real);
}
See also in C# and F#:
https://msdn.microsoft.com/it-it/library/ee340240.aspxhttps://msdn.microsoft.com/en-us/library/bb399409%28v=vs.110%29.aspx