DLang Front Page Code Example
Nicholas Londey via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed May 21 22:36:39 PDT 2014
I was looking at this code the other day and thought to my self
"This is terrible D" in the order of the C hello world with no
error handling and returning a junk stack value.
I am a reasonably experienced C++ programmer but still a newbie
at D. However, between the ideals of reusable code and no raw
loops I felt there must be a better way.
https://www.youtube.com/watch?v=cQkBOCo8UrE
http://channel9.msdn.com/Events/GoingNative/2013/Cpp-Seasoning
So I tried rewriting the example on the dlang.org home page and
came up with the following.
import std.algorithm, std.exception, std.stdio;
double average(T)(T range)
{
enforce(!range.empty, "No inputs");
auto totals = range.map!(a => tuple(1.0,
cast(double)(a))).reduce!((a, b) => tuple(a[0] + b[0], a[1] +
b[1]));
return totals[1] / totals[0];
}
void main()
{
writeln("Average line length: ", stdin.byLine.map!(a =>
a.length).average);
}
In doing so I ran into a few issues.
- Average or mean did not seem to already exist in algorithm or
numeric.
- I could not think of an easy way to add component wise binaryOp
to a Tuple.
- Tried using static array instead of tuple but could not work
out how to crate a static array as the result of a lambda.
- Using dynamic array caused a compile issue and presumably would
have had terrible heap garbage.
I am not necessarily saying we should replace the existing
example but was curious what other people thought.
More information about the Digitalmars-d-learn
mailing list