Bug 14034 – std.algorithm.mean

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2015-01-23T14:31:46Z
Last change time
2017-12-18T22:57:15Z
Assigned to
No Owner
Creator
bearophile_hugs

Comments

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.aspx https://msdn.microsoft.com/en-us/library/bb399409%28v=vs.110%29.aspx
Comment #1 by jack — 2015-09-02T17:38:30Z
Comment #2 by jack — 2015-09-30T20:48:59Z
Comment #3 by github-bugzilla — 2017-11-22T04:18:07Z
Comment #4 by github-bugzilla — 2017-12-18T22:57:15Z