Skip to content

Commit b5ae51c

Browse files
authored
Merge pull request #1711 from ZombineDev/patch-4
Make average line length example more concise and move it to the top merged-on-behalf-of: Vladimir Panteleev <github@thecybershadow.net>
2 parents ecdaa07 + 634f9a3 commit b5ae51c

File tree

1 file changed

+28
-10
lines changed

1 file changed

+28
-10
lines changed

index.dd

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,27 @@ $(DIVC intro, $(DIV, $(DIV,
3030
)
3131
$(DIVID your-code-here-default,
3232
$(RUNNABLE_EXAMPLE
33+
$(RUNNABLE_EXAMPLE_STDIN
34+
The D programming language
35+
Modern convenience.
36+
Modeling power.
37+
Native efficiency.)
38+
----
39+
// Compute average line length for stdin
40+
void main()
41+
{
42+
import std.range, std.stdio;
43+
44+
auto sum = 0.0;
45+
auto count = stdin.byLine
46+
.tee!(l => sum += l.length).walkLength;
47+
48+
writeln("Average line length: ",
49+
count ? sum / count : 0);
50+
}
51+
----
52+
)
53+
$(EXTRA_EXAMPLE
3354
$(RUNNABLE_EXAMPLE_STDIN 2.4 plus 2.4 equals 5 for sufficiently large values of 2.)
3455
----
3556
// Round floating point numbers
@@ -243,20 +264,17 @@ Modern convenience.
243264
Modeling power.
244265
Native efficiency.)
245266
----
246-
#!/usr/bin/env rdmd
247-
import std.range, std.stdio;
248-
249267
// Compute average line length for stdin
250268
void main()
251269
{
252-
ulong lines = 0, sumLength = 0;
253-
foreach (line; stdin.byLine())
254-
{
255-
++lines;
256-
sumLength += line.length;
257-
}
270+
import std.range, std.stdio;
271+
272+
auto sum = 0.0;
273+
auto count = stdin.byLine
274+
.tee!(l => sum += l.length).walkLength;
275+
258276
writeln("Average line length: ",
259-
lines ? cast(double) sumLength / lines : 0.0);
277+
count ? sum / count : 0);
260278
}
261279
----
262280
))

0 commit comments

Comments
 (0)